MST

星途 面试题库

面试题:C++中const成员函数与非const成员函数的重载及调用规则

在C++类中,有两个同名成员函数,一个是const修饰的,另一个不是。请详细说明在何种情况下会调用const版本的函数,何种情况下会调用非const版本的函数,并且分析当类对象本身是const时,调用这两种函数会出现什么情况,为什么?
37.7万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
  1. 调用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对象调用。
  2. 调用非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版本。
  3. 当类对象本身是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成员函数。