继承和指向指针的指针:为什么它不起作用以及如何解决它?
当我使用指向继承类的指针调用基类函数时,为什么会出现编译错误?
示例:
class cFoo {};
class cBar : public cFoo {};
void func1(cFoo *) {} // base class
void func2(cFoo **) {} // base class
void main(void)
{ cBar bar, *pbar; // inherited class
func1(&bar); // compiles OK
func2(&pbar); // fail
func2(dynamic_cast<cFoo**>(&pbar)); // 'class cFoo ** ' : invalid target type for dynamic_cast
}
我该如何解决这个问题?
Why do I get a compilation error when I call a base-class function with a pointer to a pointer to an inherited class?
Example:
class cFoo {};
class cBar : public cFoo {};
void func1(cFoo *) {} // base class
void func2(cFoo **) {} // base class
void main(void)
{ cBar bar, *pbar; // inherited class
func1(&bar); // compiles OK
func2(&pbar); // fail
func2(dynamic_cast<cFoo**>(&pbar)); // 'class cFoo ** ' : invalid target type for dynamic_cast
}
How do I get around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
考虑以下情况:
如果这样做有效,您将设法将 cFoo 对象放入 cBar 指针中,而不会出现编译器错误,并且类型系统将被破坏。动态施法不会有帮助,因为施法无法防止损坏。
Consider the following:
If that worked, you would have managed to put a cFoo object into a cBar pointer with no compiler error, and the type system would be subverted. A dynamic cast would not help, since there is no way the cast could prevent the damage.
它不起作用,因为
dynamic_cast
适用于类的指针或引用。并且您尝试在指向指针的指针上使用它。简单的修复方法如下:
It doesn't work because
dynamic_cast
works on pointers or references to classes. And you're trying to use it on pointers to pointers.The simple fix would be something like this:
你试图做的事情是有缺陷的。
(非常量)指向指针的指针作为函数参数的典型用例 - 是函数将修改参数以指向某个实例的指针。
这是选择实例的函数。
工厂方法示例。
参数的类型描述了函数保证有效的类型。
如果您的函数保证该实例是 cBar,那么它应该采用 cBar** 参数。
由于它需要一个 cFoo** 它只保证该对象是一个有效的 cFoo。
在当前形式中,如果强制强制转换,将导致任何类型的 cFoo 暴露为 cBar - 即使情况并非如此。
What you are trying to do is flawed.
The typical use case for a (non const) pointer-to-a-pointer as a function argument - is that the function will modify the argument to point to a pointer of some instance.
It is the function that chooses the instance.
Example a factory method.
The type of argument describes the type that the function guarantees to be valid.
If your function guaranteed that the instance was a cBar then it should take a cBar** argument.
As it takes a cFoo** it only guarantees that the object is a valid cFoo.
In the current form if you force a cast you will cause any type of cFoo to be exposed as a cBar - even if that is not the case.