- 使用类的组合(线段Line类中包含点Point类成员):
#include <iostream>
#include <cmath>
using namespace std;
//Point类的定义
class Point {
public:
Point(int xx = 0, int yy = 0) {
//构造函数定义了,类外无需实现
x = xx;
y = yy;
}
Point(Point &p);//复制构造函数声明
int getX() {
return x; }//成员函数
int getY() {
return y; }//成员函数
private:
int x, y;
};
Point::Point(Point &p) {
//复制构造函数的实现
x = p.x;
y = p.y;
cout << "Calling the copy constructor of Point" << endl;
}
//类的组合
class Line {
//Line类的定义
public:
Line(Point xp1, Point xp2);//组合类Line的构造函数的声明(这里只有对象(Point类对象)成员所需的形参,无本类成员所需的形参)
Line(Line &l);//复制构造函数声明
double getLen() {
return len; }//成员函数
private://私有成员当中,有两个Point类的对象成员p1,p2
Point p1, p2; //Point类的对象p1,p2
double len;
};
//组合类的构造函数
Line::Line(Point xp1, Point xp2) : p1(xp1), p2(xp2) {
//参数表内形实结合,生成两个局部的Point类对象xp1和xp2(调用了两次Point类复制构造函数),
//然后初始化列表,用已有的对象(xp1和xp2)去初始化新Point类对象p1、p2(再次调用两次Point类复制构造函数)
cout << "Calling constructor of Line" << endl;
double x = static_cast<double>(p1.getX() - p2.getX());
double y = static_cast<double>(p1.getY() - p2.getY());
len = sqrt(x * x + y * y);
}
//组合类的复制构造函数
Line::Line(Line &l) : p1(l.p1), p2(l.p2) {
//用已有的 Line类的对象l来初始化新的Line类对象(l是对象line的引用)
//初始化列表遵循的规则跟组合类构造函数是一样的!要列出对象1(参数),对象2(参数),...
cout << "Calling the copy constructor of Line" << endl;
len = l.len;
}
//主函数
int main() {
Point myp1(1, 1), myp2(4, 5); //建立Point类的对象
Line line(myp1, myp2); //建立Line类的对象
Line line2(line); //利用拷贝构造函数建立一个新对象
cout << "The length of the line is: ";
cout << line.getLen() << endl;
cout << "The length of the line2 is: ";
cout << line2.getLen() << endl;
return 0;
}
- 使用友元函数
#include <iostream>
#include <cmath>
using namespace std;
class Point {
//Point类定义
public: //外部接口
Point(int x = 0, int y = 0) : x(x), y(y) {
}
int getX() {
return x; }
int getY() {
return y; }
friend float dist(Point &p1, Point &p2); //友元函数声明
private: //私有数据成员
int x, y;
};
float dist(Point &p1, Point &p2) {
//友元函数实现
double x = p1.x - p2.x; //通过对象访问私有数据成员
double y = p1.y - p2.y;
return static_cast<float>(sqrt(x * x + y * y));
}
int main() {
//主函数
Point myp1(1, 1), myp2(4, 5); //定义Point类的对象
cout << "The distance is: ";
cout << dist(myp1, myp2) << endl; //计算两点间的距离
return 0;
}