【问题标题】:How to get a const reference to an object and change the object using that reference (Using const_cast)?如何获取对对象的 const 引用并使用该引用更改对象(使用 const_cast)?
【发布时间】:2011-12-13 02:51:28
【问题描述】:

我有一个成员函数返回一个const 对类实例的引用。

例子:

class State
{
  const City* city1;
public:
  State(const City& c) : city1(c) {}
  const City& getReference() const {return *city1;}
  void changeStuff();
};

如何使用 const_cast 和 getReference() 获得指向 city1 的非 const City *

此外,通过执行以下操作,我能够在不使用 const_cast 的情况下实现我想要的: (假设已经有一个名为state1的State实例)

City ref = state1.getReference(); //Why does it work?
City * ptr = &ref; //This is what I wanted, but not this way
ref->changeStuff(); //How can I call functions changing things if the reference was constant?

如何从返回 const 引用甚至调用 setter 的函数中获取非 const 引用?

感谢您的关注

【问题讨论】:

  • 为什么需要非常量指针?这似乎违反了 constness 的全部目的。
  • 我也想问和templatetypedef一样的问题。如果你想“入侵”,请明确澄清,这样人们就不会说你的设计是错误的来唠叨你。
  • 这有点令人费解。首先,您的 State 类甚至不是有效的 C++ 代码(您将引用扔到 ctor 中的指针中)。然而,更令人困惑的是changeStuffState 的成员,但您想用City 对象调用它(这两种类型是否发生相同的方法?为什么还要在这里提到它?)。此外,您的 ref 变量不是参考。

标签: c++ oop const-cast


【解决方案1】:
City ref = state1.getReference(); //Why does it work?

它有效,因为那不是参考。您正在制作 const 值的副本。试试这个:

City & ref = state1.getReference();

那是行不通的。你可以像这样使用 const cast:

City * ptr = const_cast<City*>(&state1.getReference());

只要确保对象不是真正的 const。否则,实际尝试修改它是未定义的行为。

【讨论】:

    【解决方案2】:

    如果你声明了某个东西是const,就像你向编译器做出承诺一样,你永远不会改变那个东西的内容,你为什么要这么做?

    如果你真的想改变 const 类型中的某些东西,你必须声明 mutable:

    class A
    {
    public:
    mutable int _change_me;
    };
    

    现在您可以更改成员 _change_me,即使您有 class A 的 const 引用。

    【讨论】:

    • 事实并非如此。引用是恒定的,这并不一定意味着它所引用的对象也是恒定的。
    猜你喜欢
    • 2012-01-29
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多