传递指针到派生类,函数期望指向基类的指针? [英] Passing pointer to derived class, to function that expects pointer to base class?

查看:163
本文介绍了传递指针到派生类,函数期望指向基类的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的。我不是很好的多态性在C + +,但我现在有一个问题。想象这些类:

OK. I'm not very good at polymorphism in C++, but I've a problem now. Imagine these classes:

class Parent {
public:
     Parent();
     virtual ~Parent();
};

class Child : public Parent
{
public:
     Child();
};

class Director
public:
     Director();
     void doStuff(Parent* p);
};


// Assume we have a instance of Director, and call the doStuff function here:
doStuff(new Child()); // Gives error

我得到错误

无法将参数1从Child *转换为Parent *

cannot convert parameter 1 from 'Child *' to 'Parent *'

是,为什么这不工作?
我需要做任何类型的铸造或什么,或什么是问题?

And my simple question is, WHY this doesn't work? Do I need to do any sort of casting or what, or what is the problem?

EDIT:
我把所有的文件在这里,因为他们是。
我认为问题在于我的包含,因为我真的不知道如何应该用#ifndef和这样做。请检查出来。

Director.h: http://pastebin.com/2uJqezju

Director.cpp: http://pastebin.com/SZ6cuBJC

IApp.h: http://pastebin.com/euCAwpnL

IApp.cpp: http://pastebin.com/JHDuQUhW

IScene:h: http://pastebin.com/cweH9G6p

IScene.cpp: http://pastebin.com/9epW0dRA

I put all my files here as they are. I think the problem lies in my inclusions, since I really dont have any idea of how it's supposed to be done with #ifndef and such. Please check them out.
Director.h: http://pastebin.com/2uJqezju
Director.cpp: http://pastebin.com/SZ6cuBJC
IApp.h: http://pastebin.com/euCAwpnL
IApp.cpp: http://pastebin.com/JHDuQUhW
IScene:h: http://pastebin.com/cweH9G6p
IScene.cpp: http://pastebin.com/9epW0dRA

然后我已创建了一些实例:

GameApp.h(继承EDGE :: IApp): http: //pastebin.com/QbjbVqSi

GameApp.cpp: http:// pastebin。 com / sYJvmbeP

GameScene.h(继承EDGE :: IScene): http:/ /pastebin.com/K1WYNvRf

GameScene.cpp: http://pastebin.com / uJx3FLBW

Then I have created some instances of it:
GameApp.h (inherits EDGE::IApp): http://pastebin.com/QbjbVqSi
GameApp.cpp: http://pastebin.com/sYJvmbeP
GameScene.h (inherits EDGE::IScene): http://pastebin.com/K1WYNvRf
GameScene.cpp: http://pastebin.com/uJx3FLBW

不要害怕检查它们,实际上每行中有10行代码他们。但问题是在GameApp.cpp中,我尝试创建一个GameScene的实例,并将其传递给Director-> createNewScene(IScene * scene)。

Don't be afraid to check them out, there are really like 10 lines of code in each of them. But the problem is in GameApp.cpp where I try to create an instance of GameScene, and pass it to the Director->createNewScene(IScene* scene).

推荐答案

Director.h:

Director.h:

class IScene;

应在命名空间内

这篇关于传递指针到派生类,函数期望指向基类的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆