代码之家  ›  专栏  ›  技术社区  ›  jkeys

为什么C++中不允许非const转换为cont?

  •  2
  • jkeys  · 技术社区  · 17 年前

    我有两名getter成员:

    Node* prev() { return prev_; }
    int value()  { return value_ }
    

    请注意缺少常量标识符(我忘记了它们,但现在我想知道为什么这不起作用)。我正在尝试编译以下内容:

    Node(Node const& other) : prev_(other.prev()), value_(other.value()) { }
    

    {
       Foo(int bar);
    }
    
    Foo(const int bar)
    {
       //lala
    }
    

    为什么它不让我用复制构造函数做同样的事情呢?常量标识符意味着我承诺不更改任何内容,那么,如果我从常量或非常量源获取值,又有什么关系呢?

    5 回复  |  直到 16 年前
        1
  •  14
  •   JaredPar    17 年前

        2
  •  3
  •   Johannes Schaub - litb    17 年前

    我认为C++允许非const转换函数函数,例如:

    Node const 到 Node& 用于约束 this 指针)。因此,它将删除const-not allowed,因为它将调用const对象上的非const函数。

    /* class Foo */ {
       Foo(int bar);
    }
    
    /* Foo:: */ Foo(const int bar)
    {
       //lala
    }
    

    const 参数只会在函数体内部局部产生影响-它不会对调用方产生任何影响)。此外,此代码不包含任何调用(假设第一个块位于某个函数内)。

    如果你想知道:如果上面的两个版本是相同的-为什么下面的不是?这是因为下面包含另一个间接层次:下面是引用本身( 常数 但引用的类型是const。此时,const正在运行 在确定函数类型时被忽略。

    /* class Foo */ {
       Foo(int &bar);
    }
    
    // different thing, won't work!
    /* Foo:: */ Foo(const int &bar)
    {
       //lala
    }
    
        3
  •  2
  •   Tyler McHenry    17 年前

    你是对的-const意味着你承诺不改变任何事情。编译器不允许您调用对象上的方法,而这些方法本身并不保证不会更改任何内容,从而使您遵守承诺。

        4
  •  2
  •   atomice    17 年前

    Node(Node const& other) 争论 other 宣布 const . 这意味着你只能打电话 常数 方法。

    你在打电话吗 other.prev() other.value() 从构造函数中,两者都是非- 方法,因此编译器会抱怨。

        5
  •  2
  •   Michael Burr    17 年前

    正如其他人所提到的,您正在对const对象调用非const方法,而编译器不允许这样做。

    一个简单的修复方法是将getter函数标记为const:

    Node* prev() const { return prev_; }
    int value()  const { return value_; }
    

    因为它们不修改对象;现在可以使用const对象调用它们。事实上,无论如何都应该这样做,这样类的用户就可以使用const对象调用这些getter。

    但是,如果您的复制ctor看起来像:

    Node(Node const& other) : prev_(other.prev()), value_(other.value()) { }
    

    prev_ 成员。根据类的语义,这可能没问题,但可能是所有权问题或其他逻辑不一致。

    推荐文章