面试题答案
一键面试-
调用const版本函数的情况:
- 当通过
const
对象调用成员函数时,如果存在const
版本的同名函数,会调用const
版本的函数。例如:
class MyClass { public: void print() const { std::cout << "This is const print" << std::endl; } void print() { std::cout << "This is non - const print" << std::endl; } }; int main() { const MyClass obj; obj.print();// 这里会调用const版本的print函数 return 0; }
- 原因是
const
对象不能调用非const
成员函数,因为非const
成员函数可能会修改对象的状态,而const
对象的状态是不允许被修改的。const
版本的成员函数承诺不会修改对象的状态,所以可以被const
对象调用。
- 当通过
-
调用非const版本函数的情况:
- 当通过非
const
对象调用成员函数时,如果存在同名的const
和非const
版本函数,会调用非const
版本的函数。例如:
class MyClass { public: void print() const { std::cout << "This is const print" << std::endl; } void print() { std::cout << "This is non - const print" << std::endl; } }; int main() { MyClass obj; obj.print();// 这里会调用非const版本的print函数 return 0; }
- 原因是非
const
对象既可以调用const
成员函数,也可以调用非const
成员函数。编译器优先选择最匹配的函数,非const
对象调用时,非const
版本函数更匹配,所以会调用非const
版本。
- 当通过非
-
当类对象本身是const时:
- 只能调用
const
版本的成员函数,调用非const
版本函数会导致编译错误。例如:
class MyClass { public: void print() const { std::cout << "This is const print" << std::endl; } void print() { std::cout << "This is non - const print" << std::endl; } }; int main() { const MyClass obj; // obj.print();// 如果这里试图调用非const版本的print函数,会编译错误 obj.print();// 调用const版本函数正常 return 0; }
- 原因是
const
对象的状态必须保持不变,非const
成员函数可能会修改对象状态,这与const
对象的特性相违背,所以编译器不允许const
对象调用非const
成员函数。
- 只能调用