C++程序的一般结构

在一个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;

}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值