类中const函数及非const函数的调用规则

来源:互联网 发布:sql语句check约束 编辑:程序博客网 时间:2024/06/05 00:47

类中const函数及非const函数的调用规则

作者:t427 | 出处:博客园 | 阅读13次 2012/8/11 20:37:22
class Student { public: int getAge() { return m_age; } int getAge() const { return m_age; } void setAge(int age) { m_age = age; } void setAge(int age) const { //此处报错,提示左值不是const //m_age = age; } public: int m_age; };

 

众所周知,在相同参数及相同名字的情况下,const是可以构成函数重载的,但const成员函数不能更改任何非静态成员变量;

类中二函数都存在的情况下:

const对象默认调用const成员函数,非const对象默认调用非const成员函数;

若非const对象想调用const成员函数,则需显式转化,如(const Student&)obj.getAge();

若const对象想调用非const成员函数,同理const_cast<Student&>(constObj).getAge();(注意:constObj要加括号)

类中只有一函数存在的情况下:

非const对象可以调用const成员函数或非const成员函数;

const对象只能调用const成员函数,直接调用非const函数时编译器会报错;

 

若有一类Teacher代表老师所教的学生,假如获得一个学生如下

const Student getFirstStudent();

则有如下情况:

//错误 提示左操作数必须为左值 teacher.getFirstStudent().m_age = 15; //正确,调用了复制构造函数生成新对象 Student student = teacher.getFirstStudent(); student.m_age = 15;

应该是teacher.getFirstStudent()返回的const对象不能直接更改成员;

但赋值后调用复制构造函数,生成的student是新对象,跟返回的const没有关系,故能更改

原创粉丝点击