C++学习 类的分文件实现

mian.cpp测试文件 

#include <iostream>
using namespace std;
#include "circle.h"
#include "point.h"

void isInCircle(Point& p, Circle& c)
{
	int distence =
	(c.getCenter().getX() - p.getX())* (c.getCenter().getX() - p.getX()) +
		(c.getCenter().getY() - p.getY()) * (c.getCenter().getY() - p.getY());
	int rr = c.getR() * c.getR();

	if (distence == rr)
	{
		cout << "On the circle." << endl;
	}
	else if (distence < rr)
	{
		cout << "In the circle." << endl;
	}
	else
	{
		cout << "Out the circle." << endl;
	}
}

int main()
{
	Circle c1;
	Point center;
	center.setX(10);
	center.setY(10);
	c1.setCenter(center);
	c1.setR(5);

	Point p1;
	p1.setX(10);
	p1.setY(16);
	
	isInCircle(p1, c1);
	

	system("pause");
	return 0;
}

point.h点类的头文件,只保留点类的成员函数声明,实现放在另一个文件中

#pragma once
#include <iostream>
using namespace std;

class Point
{
public:
	void setX(int x);
	
	void setY(int y);
	
	int getX();

	int getY();
private:
	int m_X;
	int m_Y;

};

point.cpp 在成员函数前加上其所属类的作用域,并完成成员函数的实现

#include "point.h"

void Point::setX(int x)
{
	m_X = x;
}
void Point::setY(int y)
{
	m_Y = y;
}
int Point::getX()
{
	return m_X;
}
int Point::getY()
{
	return m_Y;
}

circle.h

#pragma once
#include <iostream>
using namespace std;
#include "point.h"

class Circle
{
public:
	void setCenter(Point& center);

	Point getCenter();

	void setR(int r);

	int getR();

private:
	int m_R;

	Point m_Center;
};

circle.cpp

#include "circle.h"

void Circle::setCenter(Point& center)
{
	m_Center = center;
}
Point Circle::getCenter()
{
	return m_Center;
}
void Circle::setR(int r)
{
	m_R = r;
}
int Circle::getR()
{
	return m_R;
}

通过对类的分文件实现,可以在大型项目中使我们的代码更加易于阅读和维护。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值