C++程序的一般组织结构
一个工程可以划分为多个源文件:
- 类声明文件(.h文件)
- 类实现文件(.cpp文件)
- 类的使用文件(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 宏定义指令:
- 定义符号常量,很多情况下已被const定义语句取代。
- 定义带参数宏,已被内联函数取代。
#undef: 删除由#define
定义的宏,使之不再起作用。
条件编译指令——#if 和 #endif
#if 常量表达式
//当"常量表达式"非零时编译
程序正文
#endif
......