怎么在const成员函数里面调用非const成员函

2025-04-29 14:37:26
推荐回答(1个)
回答1:

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成员函数编译器会报错。