【问题标题】:C++ inheritance, sending a pointer to base classC++继承,发送一个指向基类的指针
【发布时间】:2015-03-15 19:34:00
【问题描述】:

我有一个派生自 Creep 类的 ninjaCreep 类。我想将通过派生类的参数获得的指针传递给基类的构造函数,但是我收到了这个错误:

../ninjacreep.cpp|4|error: no match for ‘operator*’ (operand type is >‘Ogre::SceneManager’)|

代码:

ninjaCreep::ninjaCreep(Ogre::SceneManager& sceneManager, int x, int y, int z, std::string id)
        : Creep(*sceneManager, x, y ,z, id) //line 4
{
    //ctor
}

我以前从未传递过指向基类的指针,所以我认为错误出在某处?

Creep构造函数的参数与ninjaCreep相同:

Creep(Ogre::SceneManager& sceneManager, int x, int y, int z, std::string id);

【问题讨论】:

  • “我以前从未传递过指向基类的指针”——你现在也没有传递一个。那是一个参考参数;不是指针。编译器抱怨是因为*sceneManager 试图将operator * 应用于不是指针的东西,并且没有允许它的重载。丢失*
  • 你是对的,我的错(你可以想象我在使用它们大约一年后不再犯指针错误......)
  • 在这种情况下使用它们。 =P
  • 我的猜测是:: Creep(*sceneManager, x, y ,z, id) //line 4 可能需要是: Creep(&sceneManager, x, y ,z, id) //line 4。如果你想要一个指针,你需要使用&获取地址。

标签: c++ pointers inheritance constructor superclass


【解决方案1】:

您只需要按原样使用参数即可:

ninjaCreep::ninjaCreep(Ogre::SceneManager& sceneManager, int x, int y, int z, std::string id)
        : Creep(sceneManager, x, y ,z, id) //line 4 no "*"
{
    //ctor
}

sceneManager 不是指针:它是对SceneManger 类型对象的引用。它将用于普通的SceneManager 对象,没有任何取消引用。

重要提示:

& 可以是类型声明的一部分:

int a 
int &i=a ;  // i is a reference.  you can then use i and a interchangeably

不要与取址运算符混淆:

int a; 
int *pa = &a;  // pa is a pointer to a.  It contains the adress of a. 
               // You can then use *pa and a interchangeably
               // until another address is assigned to pa.  

【讨论】:

    猜你喜欢
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 2017-07-30
    • 2016-04-30
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    相关资源
    最近更新 更多