立方体类:
返回多个数据时,可以使用数组,但是需要new或static来保证数组在全局空间;
利用成员函数比较两个对象时,只需要一个形参数就行;
#include<iostream>
#include<string>
using namespace std;
//创建立方体类;
class Cube
{
private:
int m_l=0;
int m_w=0;
int m_h=0;
public:
//设置长宽高;
void Getparam(int l,int w,int h)
{
m_l = l;
m_w = w;
m_h = h;
}
//读取长宽高;//这里采用数组的方式返回多个值,
int* Readparam()
{ //为了保证数组空间在全局变量中,采用new或者static的方式;
int* a= new int[3];
a[0] = m_l;
a[1] = m_w;
a[2] = m_h;
return a;
}
//比较是否一样;
//这里利用成员函数时调用只需要一个参数;
bool IsSame(Cube &c) {
if (m_l == *(c.Readparam()) && m_l == *(c.Readparam() + 1) && m_l == *(c.Readparam() + 2))
return true;
else
return false;
}
};
int main()
{
Cube c1;
c1.Getparam(10, 10, 10);
int* p= c1.Readparam();
cout << "长宽高为:" << *p <<"/" << *(p + 1) <<"/" << *(p + 2) << endl;
Cube c2;
c2.Getparam(10, 11, 10);
if (c1.IsSame(c2))
{
cout << "两个长方体相同" << endl;
}
else
cout << "两个长方体不同" << endl;
system("pause");
return 0;
}
判断点和圆形的关系
在类中嵌套使用类;
#include<iostream>
#include<string>
using namespace std;
//判断点和圆形的关系;
// 创建点类;
class Point
{
private:
int m_x=0;
int m_y=0;
public:
//设置点的坐标;
void SetPiont(int x, int y)
{
m_x = x;
m_y = y;
}
//读取点的坐标;
int GetX()
{
return m_x;
}
int GetY()
{
return m_y;
}
};
//创建圆形类;
class Circle
{
private:
//半径;
int m_r = 0;
//圆心;
Point m_center;
public:
void SetR(int r)
{
m_r = r;
}
int GetR()
{
return m_r;
}
//设置圆心;
void SetCenter(Point center)
{
m_center = center;
}
//获取圆心;
Point GetCenter()
{
return m_center;
}
};
int main()
{
//设置圆;
Circle c;
c.SetR(10);
Point center;
c.SetCenter(center);
center.SetPiont(10, 0);
//设置点;
Point p;
p.SetPiont(10, 10);
//计算点和圆心的距离
int l = (p.GetX() - center.GetX()) * (p.GetX() - center.GetX())
+ (p.GetY() - center.GetY()) * (p.GetY() - center.GetY());
//判断点和圆的关系;
if (l > (c.GetR() * c.GetR()))
cout << "点在圆形外:" << endl;
else if(l == (c.GetR() * c.GetR()))
cout << "点在圆形上:" << endl;
else
cout << "点在圆形内:" << endl;
system("pause");
return 0;
}