C++学习日记——头文件的编写

目录

1. 头文件概述

2. 头文件编写格式及要求

3. 头文件引用的源文件编写要求

4. 主函数的调用

5. 其他函数...

6. 放松时刻


1. 头文件概述

对于一些大型程序而言,分文件编写尤为重要,进而引申出了编写头文件的相关需求。

2. 头文件编写格式及要求

2.1 第一步,在第一行写明,#program once,主要是为了防止头文件被重复引用。由于是第一次接触,详细还请参照这篇文章。->C语言 #pragma once - C语言零基础入门教程

2.2 第二步,引入代码使用的头文件;

2.3 第三步,将头文件所引用的文件的变量,及函数的声明写入头文件中。

如:Circle.h

#pragma once
#include <iostream>
#include "Point.h"    // include写好的点类头文件

using namespace std;

class Circle    // 定义一个圆的类
{
	Point Cir_cen;    // (点类)圆心
	int Cir_R;    // 半径
public:
	void setCir(int x, int y, int r);    // 初始化圆的属性

	int Get_R();    // 得到圆的半径
	double Distance(Point& p);    // 判断一个点和圆的关系
};

3. 头文件引用的源文件编写要求

3.1 第一步,include编写过程中用到的头文件,和对应的头文件;

3.2 第二步,编写函数,对于头文件中声明的函数,应当在函数名前面写清楚函数的作用域是哪个类的。

如:Circle.cpp

#include<iostream>
#include"Circle.h"


void Circle::setCir(int x, int y, int r) 
{ 
	Cir_cen.Set_x(x); 
	Cir_cen.Set_y(y);
	Cir_R = r;
}

int Circle::Get_R()
{
	return Cir_R;
}

double Circle::Distance(Point& p)
{
	return pow((
		pow((p.Get_x() - Cir_cen.Get_x()), 2) +
		pow((p.Get_y() - Cir_cen.Get_y()), 2)
		), 0.5);    // 计算点到圆心的距离
}

4. 主函数的调用

main.cpp

#include <iostream>
#include <math.h>
#include "Point.h"
#include "Circle.h"

using namespace std;

int main()
{
	Circle c;
	Point p;
	int x, y, r;   // 点的坐标(x, y)和圆的半径
	double dis;    // 两点间距离
	cout << "依次输入圆心的坐标(x, y)和半径:";
	cin >> x >> y >> r;
	c.setCir(x, y, r);
	cout << "输入点的坐标(x, y):";
	cin >> x >> y;

	p.Set_x(x); p.Set_y(y);
	dis = c.Distance(p);

	if (dis != c.Get_R())
	{
		if (dis > c.Get_R()) {
			cout << "点在圆外,距离圆心" << dis << "处" << endl;
		}
		else {
			cout << "点在圆内,距离圆心" << dis << "处" << endl;
		}
	}
	else
	{
		cout << "点在圆上" << endl;
	}

	system("pause");
	return 0;
}

5. 其他函数...

Point.h

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

class Point
{
	int P_x;
	int P_y;
public:
	void Set_x(int x);
	void Set_y(int y);
	int Get_x();
	int Get_y();
};

 Point.cpp

#include "Point.h"

void Point::Set_x(int x) 
{
	P_x = x;
}

void Point::Set_y(int y) 
{ 
	P_y = y;
}

int Point::Get_x()
{ 
	return P_x;
}

int Point::Get_y()
{ 
	return P_y;
}

6. 放松时刻

  • 19
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值