我遇到了一种情况,我从函数中获取对指针的引用作为返回类型。引用很重要,因为我需要调用代码才能修改指针。
但我也希望能够通过另一个函数返回它,这次转换为派生类型的引用指针。这导致了编译器错误,我无法完全弄清楚如何解决。
这个程序显示了我正在尝试做的事情:
#include <iostream>
class Foo
{
public:
virtual ~Foo() {}
};
class Bar : public Foo
{
public:
virtual ~Bar() {}
void doit() { std::cout << "Done" << std::endl; }
};
class Container
{
public:
void setFoo(Foo *f) { _foo = f; }
Foo*& getFoo() { return _foo; }
Foo *_foo;
};
class OtherContainer : public Container
{
public:
void setBar(Bar *b) { setFoo(dynamic_cast<Foo*>(b)); }
Bar*& getBar()
{
return static_cast<Bar*&>(getFoo());
}
};
int main(int argc, char *argv[])
{
OtherContainer container;
Bar bar;
Bar otherBar;
container.setBar(&bar);
container.getBar() = &otherBar;
return 0;
}
编译器返回此错误:
g++ refptr.cc -o refptr
refptr.cc: In member function ‘Bar*& OtherContainer::getBar()’:
refptr.cc:41:20: error: invalid ‘static_cast’ from type ‘Foo*’ to type ‘Bar*&’
41 | return static_cast<Bar*&>(getFoo());
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
make: *** [<builtin>: refptr] Error 1
我尝试将静态转换更改为
有没有办法实现我想要做的事情?
经过一番闲逛,我发现让它工作的一种方法是将内部 getter 的返回值转换为指针。然后reinterpret_cast它并取消引用以返回到外部getter:
class OtherContainer : public Container
...
Bar*& getBar()
{
Foo **ptr = &getFoo();
return *reinterpret_cast<Bar**>(ptr);
}
...
正如我在对 Passer By 评论的回答中所解释的,我/仅/可以这样做,因为(在我正在制作的完整上下文中)我绝对知道存储的指向基类(Foo)的指针实际上是指向派生类(Bar)。