类的常数据成员

来源:互联网 发布:苹果手机网络不可用 编辑:程序博客网 时间:2024/05/07 11:28
#include <iostream>using namespace std;#include <string.h>struct Time{    int year;    int month;    int day;};class Teacher{    private:                               //这里的对象成员包括,id,name,参加工作时间        static int tea_count;              //计数        const Time AttendJobTime;          //结构体 变量属于这个类的常对象成员        int id;        char *name;    public:        Teacher();        Teacher(int NewId,char *NewName, Time NewTime);        Teacher(Teacher &NewTeacher);        ~Teacher();        void TeaOutput();        void JobTimeOutput() const;       //类的常函数只能调用其他常函数以及常成员不能调用非常部分};int Teacher::tea_count = 0;Teacher::Teacher():AttendJobTime()             //默认构造函数{    tea_count ++ ;    id = 0;    name = new char[20];    strcpy(name,"默认名字");}Teacher::Teacher(int NewId, char * NewName, Time NewTime):id(NewId),AttendJobTime(NewTime)  ///常量必须在外面赋值{    tea_count ++;    //id = NewId;     这里已经在构造函数名后面实现了    name = new char[20];    strcpy(name,NewName);}Teacher::Teacher(Teacher &NewTeacher):AttendJobTime(NewTeacher.AttendJobTime)    //拷贝构造函数{    tea_count ++;    id = NewTeacher.id;    name = new char[20];    strcpy(name,NewTeacher.name);}Teacher::~Teacher()         //析构函数{    if(name)    {        delete []  name;        name = NULL;    }}void Teacher::TeaOutput(){    cout<<endl<<"现在共有"<<tea_count<<"名教师!"<<endl;    cout<<id<<'\t'<<name<<'\t'<<endl;}void Teacher::JobTimeOutput()   const{    cout<<"参加工作的时间是:"<<AttendJobTime.year<<"年\t"<<AttendJobTime.month<<"月\t"<<AttendJobTime.day<<"日"<<endl;}int main(){    Time temTime = {2004,7,12};    Teacher WangLiang;    WangLiang.TeaOutput();    WangLiang.JobTimeOutput();    cout<<"______________________________________________________________________"<<endl;    Teacher LiHong(1100,"李 宏",temTime);                    //调用参数,有初始化列表    LiHong.TeaOutput();    LiHong.JobTimeOutput();    return 0;}///类的常数据成员必须在对象构造时同步初始化,因此每一个构造函数后面都要对类的常数据成员初始化

总结:

1、类的常数据成员必须在构造的时候出初始化,一旦定义不能改变;

2、类的常数据成员初始化时通过构造函数的初始化表列(初始化表列是在函数传参括号的后面用冒号“:”分隔,跟在构造函数的名字后的初始化序列,它将构造函数的参数直接赋值给类内的成员)类的普通成员也可以用初始化表列来初始;

3、类的常成员函数在一般函数的构造后面加 const 声明(声明和定义都要有const),它只能调用类的" 常 "部分(常成员,常函数...)不能调用非" 常 "部分;

原创粉丝点击