在一个C++项目中,至少要划分3个文件:
(1)类定义文件(*.h文件)
(2)类实现文件(*.cpp文件)
(3)类的使用文件(*.cpp文件)
通过一个例子了解C++编程中的多文件组织结构:
//文件1,类的定义,point.h
class point{ //类的定义
public: //外部接口
point(int x=0,int y=0):x(x),y(y){}
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,主函数,main.cpp
#include "point.h"
#include<iostream>
using namespace std;
int main(){
point a(4,5);
cout<<"point A: "<<a.getx()<<","<<a.gety();
point::showcount();
point b(a);
cout<<"point B: "<<b.getx()<<","<<b.gety();
point::showcount();
return 0;
}