我有一个带有指针的结构。我想这样做,如果一个结构实例是常量,那么它的指针的内容就不能被修改。
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/