C++之多文件结构在C++程序中的使用

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

改写下面定义好的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;
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值