c++ - 通过 constness 从结构传递到它的指针和引用成员

标签 c++ constants

我有一个带有指针的结构。我想这样做,如果一个结构实例是常量,那么它的指针的内容就不能被修改。

struct Foo {};

struct Bar {
    Foo /*const goes here if `const Bar`*/ *foo;
};

void f(Bar& bar) {
    *bar.foo = Foo(); // OK
}

void g(const Bar& bar) {
    *bar.foo = Foo(); // OK - but should be error
}

有没有办法将常量从结构传递到它的指针和引用成员?

最佳答案

封装来拯救!

只需通过接口(interface)编码访问:

struct Bar {
  Foo * getFoo() { return foo; }
  Foo const * getFoo() const { return foo; }
private:
  Foo *foo;
};

void f(Bar& bar) {
    *bar.getfoo() = Foo(); // OK
}

void g(const Bar& bar) {
    *bar.getfoo() = Foo(); // Error!
}

关于c++ - 通过 constness 从结构传递到它的指针和引用成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46126924/

相关文章:

c++ - CMake 没有为编译器使用适当的输出命令行参数

c++ - 如何修复 'Undefined symbols for architecture x86_64: "_get_driver_instance"' 链接器错误

C++ clang链接器问题

c++ - 是否允许并接受用删除标记静态方法?

c++ - C++中同类的静态成员变量

c++ - 在某些情况下,将对象标记为 const 会产生更好的优化代码(当使用优化进行编译时)?

iOS - 本地化静态常量

c# - 具有许多常量的智能感知(嵌套?)

c - Strtol函数的实现——cast

c++ - 从 C++ 文件中读取后,如何将常规字符串数组转换为 const 字符串数组?