为什么const限定符不能处理const对象上的指针成员? [英] Why isn't the const qualifier working on pointer members on const objects?

查看:233
本文介绍了为什么const限定符不能处理const对象上的指针成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这已经被问了很多,但我能找到的唯一的答案是当const实际上被丢弃使用(int *)或类似。为什么没有const限定符在const对象上处理指针类型成员变量时,不涉及转换。

I know this has been asked a lot, but the only answers I could find was when the const-ness was actually casted away using (int*) or similar. Why isn't the const qualifier working on pointer type member variables on const objects when no cast is involved?

#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 ):

The code above yields the following output (tested in gcc 4.5.2 and vc100):


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


推荐答案

当foo实例是const时,它的数据成员也是const,但这对于指针的适用方式不同于你最初想到的:

When a foo instance is const, its data members are const too, but this applies differently for pointers than you might at first think:

struct A {
  int *p;
};

A const obj;

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

The type of obj.p is int * const, not int const *; that is, a constant pointer to int, not a pointer to constant int.

另一种方法来看看它,让我们从一个函数开始:

For another way to look at it, let's start with a function:

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



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

Now imagine we have an A instance, and we make it const. You can imagine that as applying const_ on each data member.

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表明添加const不是 将const添加到类型的文本文本。

The variable be_wary_of_where_you_place_const shows that "adding const" is not the same as prepending "const" to the literal text of a type.

这篇关于为什么const限定符不能处理const对象上的指针成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆