使用基指针来使用派生对象函数

using base pointer to use derived objects functions

如何获取 Base 指针以实例化派生对象并使用其函数?有没有办法像 java 这样类型转换? 考虑这个示例代码:

int main(){
    cBase *pBase = 0;
    if (1 < 2)
    {
        pBase = new cDerived;
    }
}

class cBase
 {public:
     virtual void printMe()
          {
             std::cout << "printed cBase" << endl;
           }
};

class cDerived: public cBase
{public:
    virtual void printMe()
         {
            std:: cout << "printed cDerived" << endl;
          }
};

但是当我这样做时;它给我一个错误 "Expression must have class type".

cBase *pBase = 0;
    if (1 < 2)
    {
        pBase = new cDerived;
        pBase.printMe();
    }

像这样修复

#include <iostream>
using namespace std;

class cBase
 {
    public:
        virtual ~cBase() {};
        virtual void printMe()
        {
         std::cout << "printed cBase" << endl;
        }
};

class cDerived: public cBase
{public:
    virtual void printMe()
         {
            std:: cout << "printed cDerived" << endl;
          }
};

int main(){
    cBase *pBase = 0;
    if (1 < 2)
    {
        pBase = new cDerived;
        pBase->printMe();
        delete pBase;
    }
}

修复步骤。

  1. cBasecDerived class 声明之后移动 main 函数,或者在 [= 之前​​声明那些 classes 11=].

  2. pBase.printMe() 更改为 pBase->printMe()。由于 pBase 是一个指针,您必须在访问其成员之前取消引用它。 pBase->printMe() 就像 shorthand 对于 (*pBase).printMe()

加上一些其他的内务管理工作。删除 pBase 对象,因为您要使用指向基 class (cBase) 的指针删除派生的 class (cDerived),您必须声明基classes destructor virtual, or the cBase destructor will be called when pBase was delete when you really want the cDerived destructor to be called here.

在 C++ 中,为了获得指向 class/structure 的指针的 method/field,您必须使用 -> 运算符。