代码实践
#include <iostream>
using namespace std;
#include <string>
class Teacher
{
public:
Teacher(int age, string name, int tel_number)
: _age(age), _name(name), _tel_number(tel_number)
{}
void display_age() const
{
cout << "const" << endl;
/*_age = 19;*/ //错误,因为这是const修饰的member function 不可改变data member(准确的说是class object)!
cout << _age << endl;
}
//void display_age() //注意 这里说明const可以发送函数重载
//{
// cout << "no const" << endl;
// cout << _age << endl;
//}
void display_tel_number() const
{
cout << _tel_number << endl;
}
void revise_tel_number(int number) const
/*:_tel_number(number)*/ //错误,因此有了const就在函数体内操作吧
{
//修改电话号码
_tel_number = number; //可以修改,因为是_tel_number是multable
}
private:
int _age;
string _name;
//int _tel_number;
mutable int _tel_number;
};
int main()
{
const Teacher teacher(18, "teacher", 12345);
teacher.display_age(); //如果teacher使用了const 那么就必须存在const版本的 如果没有const 优先选择无const版本,在这里最好加上const
teacher.display_tel_number();
teacher.revise_tel_number(520);
teacher.display_tel_number();
system("pause");
return 0;
}
今天是20200317 今天重装了系统,有得(才怪)有失(很多)啊😂