gpt4 book ai didi

c++ - 为什么 const 限定符不能作用于 const 对象的指针成员?

转载 作者:可可西里 更新时间:2023-11-01 18:16:31 26 4
gpt4 key购买 nike

我知道这已经被问了很多,但我能找到的唯一答案是当使用 (int*) 或类似的东西实际上抛弃了 const-ness 时。当不涉及强制转换时,为什么 const 限定符不能作用于 const 对象上的指针类型成员变量?

#include <iostream>

class bar {
public:
void doit() { std::cout << " bar::doit() non-const\n"; }
void doit() const { std::cout << " bar::doit() const\n"; }
};

class foo {
bar* mybar1;
bar mybar2;
public:
foo() : mybar1(new bar) {}
void doit() const {
std::cout << "foo::doit() const\n";
std::cout << " calling mybar1->doit()\n";
mybar1->doit(); // This calls bar::doit() instead of bar::doit() const
std::cout << " calling mybar2.doit()\n";
mybar2.doit(); // This calls bar::doit() const correctly
}
// ... (proper copying elided for brevity)
};

int main(void)
{
const foo foobar; // NOTE: foobar is const
foobar.doit();
}

上面的代码产生以下输出(在 gcc 4.5.2 和 vc100 中测试):

foo::doit() const  calling mybar1->doit()    bar::doit() non-const         <-- Why ?  calling mybar2.doit()    bar::doit() const

最佳答案

当 foo 实例是 const 时,它的数据成员也是 const,但这对指针的应用与您最初想象的不同:

struct A {
int *p;
};

A const obj;

obj.p的类型是int * const,不是int const *;也就是说,指向 int 的常量指针,而不是指向常量 int 的指针。

从另一个角度来看,让我们从一个函数开始:

template<class T>
T const& const_(T const &x) {
return x;
}

现在假设我们有一个 A 实例,我们将其设为常量。您可以将其想象为对每个数据成员应用 const_。

A nc;
// nc.p has type int*.
typedef int *T; // T is the type of nc.p.

T const &p_when_nc_is_const = const_(nc.p);
// "T const" is "int * const".

const T &be_wary_of_where_you_place_const = const_(nc.p);
// "const T" is "int * const".
// "const T" is *not* "const int *".

变量 be_wary_of_where_you_place_const 表明“添加常量”与在类型的文字文本前添加“常量”相同。

关于c++ - 为什么 const 限定符不能作用于 const 对象的指针成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5917678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com