2012-06-01 150 views
2

可能重复:
Invoking a nonconst method on a member from a const method为什么const成员函数能够通过成员指针调用非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; 
} 

回答

4

该行为是正确的。

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

例如,下面会失败:

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

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

+0

我们还没有在类中声明S * const s,那么它如何可以是一个常量指针呢? – Kenta

2

const成员函数中的s的类型是S * const而不是S const*,这意味着指针本身是常量,而不是指针指向的对象。因此,非const的对象用于调用非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