为什么 const 成员函数能够通过成员指针调用非 const 成员函数

Why const member function is able to call non-const member function via member pointer?

本文关键字:成员 函数 const 指针 调用 为什么      更新时间:2023-10-16

可能的重复项:
从 const 方法调用成员上的非常量方法

常量成员函数

能够通过指针成员变量调用C++中的非常量成员函数,是否符合预期?下面给出的代码片段编译成功

#include <iostream>
class S {
public:
    void hi() {
        std::cout << "Hi" << std::endl;
    }
};
class T {
public:
    T()
    : s(new S())
    {}
    ~T()
    {
        delete s;
    }
    void hi() const {
        s->hi();
    }
private:
    S  * s;
};
int main(int argc, char ** argv) {
    T t;
    t.hi();
    return 0;
}

行为是正确的。

那是因为指针是const - S * s;,而不是对象。

例如,以下操作将失败:

void hi() const {
    s->hi();     //OK
    s = NULL;    //not OK
}

请记住,您不能修改s(这是一个指针),但您可以修改*s,这是实际对象。

const 成员函数中的s类型是 S * const ,而不是 S const* ,这意味着指针本身是常量,而不是指针指向的对象。因此,非常量的对象用于调用非常量函数,这是标准一致性行为。

S const * s1 = initialization1; //same as : const S *s1  = initialization1;
S * const s2 = initialization2;
s1->hi();     //error: the object is const
s1 = nullptr; //okay : the pointer is non-const
s2->hi();     //okay: the object is non-const
s2 = nullptr; //error: the pointer is const