gpt4 book ai didi

c++ - 继承和指向指针 : why doesn't it work and how do I get around it? 的指针

转载 作者:太空狗 更新时间:2023-10-29 20:07:21 24 4
gpt4 key购买 nike

当我使用指向继承类的指针调用基类函数时,为什么会出现编译错误?

例子:

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
}

我该如何解决这个问题?

最佳答案

考虑以下几点:

class cFoo {};
class cBar : public cFoo {};
void func1(cFoo *) {}
void func2(cFoo **p) { *p = new cFoo; } // modify pointee

void main(void)
{ cBar bar, *pbar; // inherited class

func1(&bar); // compiles OK

func2(&pbar);
}

如果这可行,您将成功地将一个 cFoo 对象放入一个 cBar 指针中,而不会出现编译器错误,并且类型系统将被颠覆。动态转换没有帮助,因为转换无法阻止伤害。

关于c++ - 继承和指向指针 : why doesn't it work and how do I get around it? 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3343391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com