【问题标题】:Does const keyword go before or after Type?const 关键字是在 Type 之前还是之后?
【发布时间】:2016-10-24 13:27:06
【问题描述】:

我是这样写的:

#define Parent C*
class C{
public:
    Parent parent;
    C():parent(NULL){}
};
void fun(Parent &p){
    //condition..return;
    fun(p->parent);
}

当我试图将引用参数设为常量以避免对被引用对象进行任何意外更改时,发生了一些事情。

第一:

我在Parent 之前添加了const,如下所示:void fun(const Parent &p)。但它不会在这一行编译 fun(p->parent);。 错误信息是:

Invalid arguments ' 候选者是:void fun(const C * &) '

那么:

我将const 的位置更改为:void fun(Parent const &p),突然之间,问题消失了。 为什么???有什么区别?

【问题讨论】:

  • 只需自己完成预处理器的工作,并将 Parent 替换为 C*。看一下生成的代码就明白了!
  • 如果您使用typedef 而不是#define,它会起作用。现在C* 是单独的项目,您左侧的const 只会影响C

标签: c++


【解决方案1】:

const 是如何工作的?它总是适用于它之前的东西。但是,当之前没有任何内容时,它适用于紧随其后的内容。换言之,const Type&Type const& 相同。

现在,永远不要使用预处理器宏来定义类型别名。在 C++ 中有两种方法可以做到这一点:usingtypedef。您使用宏的事实是您观察到这种特殊行为的原因。编译失败的代码展开如下:

void fun(const C*& p); // The pointee is const, but the pointer itself is not

我猜你是在p指向的对象上做事...但是这个对象是const!在第二个示例中,展开结果为:

void fun(C* const& p); // The pointee is not const, but the pointer itself is

然后,您在指针上做一些事情,但这次是指针,而不是指针,即const,所以一切都很好。如果您使用了别名或 typedef,那么在这两种情况下都会非常顺利:请参阅 this example

根据经验,您应该始终将const 放在您想要应用它的对象的右侧。这将允许您以应有的方式阅读类型:从右到左。

【讨论】:

    【解决方案2】:

    const 从右到左工作,使前一部分为 const,

    int * const p; // makes constant pointer to int
    

    除了开头的const typetype const之外,都是一样的:

    int const * p; // pointer to const int
    const int * p; // ditto
    

    所以如果父母是例如struct Parent{},那么Parent const & pconst Parent & p应该是一样的;但是,如果 Parent 是一个宏,例如C*,它们是不同的。

    【讨论】:

      猜你喜欢
      • 2011-07-27
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 2014-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多