2

Possible Duplicate:
Invoking a nonconst method on a member from a const method

Constant member functions are able to call non constant member functions via pointer member variables in C++, is it as expected? Below give code snippet is compiling successfully

#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;
}
4

2 回答 2

5

The behavior is correct.

That's because the pointer is const - S * s;, not the object.

For example, the following would fail:

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

Remember, you can't modify s (which is a pointer), but you can modify *s, which is the actual object.

于 2012-06-01T07:50:19.827 回答
2

sconst 成员函数中的类型是S * const, not 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
于 2012-06-01T07:54:40.160 回答