c++ - 请澄清 const 限定符传播

标签 c++

假设我们有如下一段代码:

class Base {
  public:
    int a = 5;
};

class Derived : public Base {
  public:
    Base *parent_ = new Base;
    Base* parent() const { return parent_; }
};

void f(const Derived *derived) {
    Base *p = derived->parent();
    p->a = 10; // <- is this correct?
}

我个人认为这里有一个问题:

In function f we take a pointer to const object of class Derived. This makes each member of it also const thus parent_ becomes const Base *. If it is const we should not have an ability to modify the object on which the pointer points.

我哪里错了?

最佳答案

This makes each member of it also const thus parent_ becomes const Base *.

不,指针本身会变成const,而不是它指向的对象。所以 parent_ 变成了 Base * const,而不是 const Base *,你的代码是有效的。

关于c++ - 请澄清 const 限定符传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37295656/

相关文章:

c++ - matlab和c/cpp之间的fwrite和fread

c++ - 在另一个全局仿函数中引用全局仿函数

c++ - 从套接字提取数据?

C++ 丢弃迭代器上的限定符 (const)

c++ - 如何从 dll 中获取没有垃圾的字符串?

c++ - 在非常大的数字序列中查找句点

c++ - 如何使用相同的参数构造嵌套类模板的对象?

c++ - 在 TCP 线程服务器 C++ 中传输文件

c++ - transform_iterator 与 std::iterators 不兼容?

c++ - Qt QNetworkAccessManager 为什么我不能在同一个主线程中并行发送超过 1 个 http 请求