在类中可以调用另一个类,作为本类的成员。(我的理解:这个时候,对于类的使用,类似于将类看作一个数据类型。)
示例:
我们有一个点类(Point) 还有一个圆类(circle),我们需要判断点和圆的位置关系(点在圆上,在圆外,在圆内)。我们在Circle类中将Point类作为一个成员使用。
#include <iostream>
#include <math.h>
using namespace std;
class Point
{
public:
void setx(int p_x)
{
x = p_x;
}
int getx()
{
return x;
}
void sety(int p_y)
{
y = p_y;
}
int gety()
{
return y;
}
private:
int x;
int y;
};
class Circle
{
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;
}
private:
Point m_Center; // the center of the circle is also a Point class
int m_R;
};
void isInCircle(Circle &c, Point &p)
{
// calculate the distance between two points
double res = pow(pow((c.getCenter().getx() - p.getx()), 2) + pow((c.getCenter().gety() - p.gety()), 2), 0.5);
if (res == c.getR())
{
cout << "the dot is on the circle!" << endl;
}
else if (res < c.getR())
{
cout << "the dot is within the circle!" << endl;
}
else
{
cout << "the dot is outside the circle! " << endl;
}
}
int main()
{
Circle c;
c.setR(10);
Point center;
center.setx(10);
center.sety(0);
c.setCenter(center);
Point p;
p.setx(10);
p.sety(10);
isInCircle(c, p);
}