主程序
#include "pch.h"
#include "Line.h"
/*//函数声明
void fun1(Point p);
Point fun2();*/
int main()
{
Point myp1(1, 1), myp2(4, 5); //建立Point类的对象
Line line(myp1, myp2); //建立Line类的对象
cout << "==================================================" << endl;
Line line2(line); //利用拷贝构造函数建立一个新对象
cout << "The length of the line is : "
<< line.getLen() << endl;
cout << "The length of the line is : "
<< line2.getLen() << endl;
return 0;
}
pch.h文件
#ifndef PCH_H
#define PCH_H
#include <iostream>
using namespace std;
class Point
{
public:
Point();
Point(int, int);
Point(const Point &);
virtual ~Point();
int Getx() { return x; }
int Gety() { return y; }
protected:
private:
int x;
int y;
};
#endif //PCH_H
pch.cpp
#include "pch.h"
Point::Point():x(1), y(2)
{
}
Point::Point(int _x, int _y)
{
x = _x; y = _y;
}
Point::Point(const Point &p)
{
x = p.x;
y = p.y;
cout << "Calling the copy constructor of Point!" << endl;
}
Point::~Point()
{
//dtor
}
Line.h
#pragma once
class Line
{
public:
Line();
Line(Line &); //复制构造函数声明
Line(Point, Point);//组合类构造函数声明
double getLen() { return len; }
~Line();
private:
Point p1, p2;
int len;
};
Line.cpp
#include "pch.h"
#include "line.h"
Line::Line():p1(1, 1),p2(2, 3)
{
}
//拷贝构造函数
Line::Line(Line &L):p1(L.p1),p2(L.p2)
{
cout << "Calling the copy constructor of Line !" << endl;
len = L.len;
}
//组合类构造函数
Line::Line(Point _p1, Point _p2) :p1(_p1), p2(_p2)
{
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()
{
}
运行结果如下(可使用单步调试查看程序具体运行过程,进行理解):