多文件结构和预编译命令

C++程序的一般组织结构

一个工程可以划分为多个源文件:

  1. 类声明文件(.h文件)
  2. 类实现文件(.cpp文件)
  3. 类的使用文件(main()所在的.cpp文件)

利用工程来组合各个文件

例: 多文件的工程

//文件1,类的定义,Point.h
#include <iostream>
using namespace std;
class Point { //类的定义

public:          //外部接口
	Point(int x = 0, int y = 0) : x(x), y(y) { count++; }
	Point(const Point &p);
	~Point() { count--; }

	int getX() const { return x; }
	int getY() const { return y; }
	static void showCount();          //静态函数成员

private:         //私有数据成员
	int x, y;
	static int count; //静态数据成员

};
//文件2,类的实现,Point.cpp
#include "Point.h"
#include <iostream>
using namespace std;

int Point::count = 0;            //使用类名初始化静态数据成员

Point::Point(const Point &p) : x(p.x), y(p.y) {
	count++;
}

void Point::showCount() {
	cout << "  Object count = " << count << endl;
}
//文件3,主函数,5_10.cpp
#include "Point.h"
#include <iostream>
using namespace std;

int main() {
	Point a(4, 5);           //定义对象a,其构造函数使count增1
	cout <<"Point A: "<<a.getX()<<", "<<a.getY();
	Point::showCount();      //输出对象个数
	Point b(a);              //定义对象b,其构造函数回使count增1
	cout <<"Point B: "<<b.getX()<<", "<<b.getY();
	Point::showCount();      //输出对象个数

    return 0;
}

在这里插入图片描述


编译预处理

#include 包含指令 : 将一个源文件嵌入到当前源文件中该点处。
#include<文件名> : 按标准方式搜索,文件位于C++系统目录的include子目录下
#include"文件名": 首先在当前目录中搜索,若没有,再按标准方式搜索。

#define 宏定义指令:

  1. 定义符号常量,很多情况下已被const定义语句取代。
  2. 定义带参数宏,已被内联函数取代。

#undef: 删除由#define定义的宏,使之不再起作用。


条件编译指令——#if 和 #endif

#if  常量表达式
 //当"常量表达式"非零时编译
     程序正文 
#endif
......

视频地址

发布了257 篇原创文章 · 获赞 28 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43283397/article/details/104442061