Bea*_*kie 1 c++ struct pointers reference
我试图找出如何将const结构引用转换为非const结构指针.
我有一个名为Foo的结构:
struct Foo
{
Foo& someFunc()
{
//do something
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
我有一个方法:
struct Bar
{
Foo* fooPointer;
void anotherFunc(const Foo& foo)
{
// set fooPointer to foo's pointer
}
};
Run Code Online (Sandbox Code Playgroud)
我会这样称呼它:
Foo foo;
Bar bar;
bar.anotherFunc(foo.someFunc());
Run Code Online (Sandbox Code Playgroud)
但是如何编写anotherFunc()?
void anotherFunc(const Foo& foo)
{
fooPointer = &foo; // <-- This doesn't work as foo is still const
}
Run Code Online (Sandbox Code Playgroud)
最好的答案是"不要那样做,这很疯狂".const Foo*如果指针类型不会用于修改对象,则更改指针类型,或者将其指定为Foo&if.
如果你真的有充分的理由抛弃const-correctness,那么就有一个演员阵容
fooPointer = const_cast<Foo*>(&foo);
Run Code Online (Sandbox Code Playgroud)
但首先要考虑为什么要这样做,以及如何防止以const对象的非const指针结束的错误.或者更糟糕的是,指向临时的指针在其消亡后徘徊.