|
改写下面定义好的Point类。在Point.h中定义类的属性及成员函数声明; 在Point.cpp中定义类的成员函数实现;在lab5_2.cpp中测试这个类。 |
|
注意多文件结构的编译、编辑方法、头文件的包含关系,观察相应的成员变量取值的变化情况。 |
参考程序
#include <iostream>
using namespace std;
class Point
{
private:
int X,Y;
public:
Point(int xx=0,int yy=0){X=xx;Y=yy;}
Point(Point &p);
int GetX(){ return X;}
void SetX(int xx){ X=xx;}
int GetY(){ return Y;}
void SetY(int yy){ Y=yy;}
};
Point::Point(Point &p)
{
X=p.X;
Y=p.Y;
cout<<"拷贝构造函数被调用"<<endl;
}
void main(void)
{
Point A(4,5);
Point B(A);
cout<<A.GetX()<<endl;
cout<<B.GetX()<<endl;
}
修改程序(多文件结构)
//头文件Point.h:
class Point
{
private:
int X,Y;
public:
Point(int xx=0,int yy=0) {
X=xx;
Y=yy;
}
Point(Point &p);
int GetX() {
return X;
}
void SetX(int xx) {
X=xx;
}
int GetY() {
return Y;
}
void SetY(int yy) {
Y=yy;
}
};
//Point.cpp文件:
#include <iostream>
#include "Point.h"
using namespace std;
Point::Point(Point &p)
{
X=p.X;
Y=p.Y;
cout<<"拷贝构造函数被调用"<<endl;
}
//Lab5_2文件:
#include <iostream>
#include "Point.h"
using namespace std;
void main(void)
{
Point A(4,5);
Point B(A);
cout<<A.GetX()<<endl;
cout<<B.GetX()<<endl;
}

本文介绍了一个简单的C++ Point类实现案例,通过多文件结构组织代码,并演示了如何使用拷贝构造函数。文章提供了完整的源代码,包括头文件、实现文件和测试文件,帮助读者理解C++类的设计和编译过程。
638

被折叠的 条评论
为什么被折叠?



