类成员初始化实例

来源:互联网 发布:大数据分析专业排名 编辑:程序博客网 时间:2024/05/21 10:05
#ifndef _STUDENT_H_#define _STUDENT_H_#include<IOSTREAM>#include<STRING>using namespace std;class Student{public:static int studentcount;//用于统计学生数static string schoolname;//学校名static const int post_code;//邮编//static const int post_code = 230601; //正确的初始化方法,静态常整型成员才可直接初始化.但是VC6.0不支持Student(string _name, const char _sex, int _age):sex(_sex){name = _name;age = _age;studentcount++;}Student(const Student &stu);//拷贝构造函数~Student(void);void info_show();string getName()const;void setName(string _name);const char getSex()const;//void setSex(const char _sex);//错误的,因为sex只能在对象创建时初始化,后面也就不能被赋值了的!!!!int getAge()const;void setAge(int _age);Student& operator=( Student & stu);//赋值运算符相当于函数,其返回结果是对象的引用,便于嵌套操作protected:string name;//string name = "张三";//错误的初始化方法const char sex; //const型变量只能在构造函数中初始化!!并且不存在赋值操作!!!//const char sex = 'W';//错误的初始化方法int age;};void Student::info_show(){cout << "Name:" << name << "  Sex:" << sex << "  Age:" << age << endl;cout <<"SchoolName:" << schoolname << "  PostCode:" << post_code << "  StudentCount:" << studentcount << endl; }Student::~Student(void){cout << "调用Student类的析构函数" << endl;}Student::Student(const Student &stu):sex(stu.getSex()){ //sex必须这么初始化!!!//由于此时的stu为const,故其只能调用const方法name = stu.getName();//sex = stu.getSex();//错误的!!!!!age = stu.getAge();studentcount++;schoolname = stu.schoolname;//post_code = stu.post_code;//错误!!!,const变量不能被赋值}void Student::setName(string _name){name = _name;}string Student::getName()const{return name;}const char Student::getSex()const{return sex;}int Student::getAge()const{return age;}void Student::setAge(int _age){age = _age;}Student& Student::operator=(Student & stu){if (this == &stu) return stu;name = stu.getName();//sex = stu.getSex();//错误的!!!age = stu.getAge();schoolname = stu.schoolname;//如果将其屏蔽,还会有值吗?有的。如果所有学生的此属性相同,可以不写此句的!!!//post_code = stu.post_code;//const 变量不能被赋值!!!return *this;}//静态成员的初始化必须在使用类之前。静态成员只可以访问静态成员,非静态成员可以直接访问静态成员。#endif //_STUDENT_H_

0 0