3
class A{
private:
    int a;
public:
    A() {a = 4;}
    const int& random1() const {return a; }
    //int&     random2() const {return a; }
    const int* random3() const {return &a;}
    //int*     random4() const {return &a;}
};

int main(){
    A objA;
    cout<<objA.random1()<<"\n";
    cout<<*objA.random3()<<"\n";
}

random2()并且random4()不允许如上定义。不知何故,我一直都知道这一点,但在编写自己的代码时从未遇到过,直到今天。

在 const 成员函数中,除了这两种情况之外,还有什么是不允许的?

对 C++ 标准文本的任何引用也会有所帮助。谢谢!

4

2 回答 2

10

首先明白那const T*是一个指向一些T不能改变的指针。要记住的第二件事是所有成员实际上都是通过this->.

所以(§9.3.1):

非静态成员函数可以声明为 const、volatile 或 const volatile。这些 cvqualifiers 影响 this 指针 (9.3.2) 的类型。

它的作用(§9.3.2):

在非静态 (9.3) 成员函数的主体中,关键字 this 是一个非左值表达式,其值是调用该函数的对象的地址。类 X 的成员函数中 this 的类型是 X*。如果成员函数声明为 const,则 this 的类型为 const X*,如果成员函数声明为 volatile,则 this 的类型为 volatile X*,如果成员函数声明为 const volatile,则 this 的类型为 const挥发性 X*。

函数上的Aconst使this指针const T*

这就是这些示例失败的原因:在int&变体中,a被访问为this->athisconst T*,所以a是 a const int。并且const int不能隐式转换为int&. 与其他功能相同。

换句话说,当一个函数是const它时,它const会对类中的所有内容产生影响,并且您不能隐式地将其const丢弃。

于 2010-07-25T19:18:15.290 回答
0

const 成员函数不能调用非常量成员函数,即使它们不更改任何成员数据。有时您需要提供同一函数的 const 和非 const 版本,因为指针隐式传递给成员函数并在重载决策中发挥作用。

于 2010-07-26T13:09:06.173 回答