协助解决C++的继承问题

Assistance with inheritance issue in C++

本文关键字:继承 问题 C++ 解决      更新时间:2023-10-16

我有 2 个C++类(A 和 B),假设 B 继承自 A。

它们都需要有一个 toString() 函数。它们是从返回基类类型的函数调用的。返回后,我想为正确的类类型调用 tostring() 函数。如果函数返回 B 类型对象,我想从 B 类调用 toString()。

我认为我的问题来自这样一个事实,即该函数返回对基类的引用,因此它从基类调用该函数。

示例类:

class A
{
  std::string toString();
};
class B
 : public A
{
  int extraThingToPrint;
  std::string toString(); //prints a different message than the A version
};

示例函数:

A otherClass::scan()
{
   if(otherVar == 'a') return A();
   else if(otherVar == 'bb') return B();
}
std::cout << scan().toString(); //if bb plz print B.toString() and not A.toString() (but if a, use A.toString())

otherClass::scan()按值返回A。当您尝试返回B()时,它会导致切片,并且仅返回A部分。返回对象的真实类型是A,无论你在函数中写什么。

您需要返回引用或 [智能] 指针才能使动态调度正常工作。

首先toString需要在基类中是虚拟的,然后需要返回指向基类或派生类对象的基类类型的引用(或指针)。像这样:

   class A
   {
      virtual std::string toString();
   };
   A* otherClass::scan()
   {
     A* ret;
     if(otherVar == 'a') 
          ret=new A();
     else if(otherVar == 'bb');
          ret=new B();
     return ret;
   }
    A* ret=scan();
    std::cout << ret->toString();
    delete ret;//delete once you are done