协助解决C++的继承问题
Assistance with inheritance issue in C++
我有 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
相关文章:
- 模板继承问题
- 我是否需要在虚拟继承类的构造函数中初始化基类以解决菱形继承问题?
- SIGSEGV 因为基/派生类的继承问题
- C++解决没有虚拟继承的钻石继承问题
- Arduino C 中的继承问题
- C++ 继承问题:未定义对"vtable"的引用
- 班级设计和继承问题
- C 继承问题错误C2084功能已经具有主体
- 如何在C++中解决网格继承问题
- 多重继承问题 C++
- "{"令牌 c++ 继承问题之前的另一个预期类名
- C 模板继承问题(警告和错误)
- 协助解决C++的继承问题
- 在我的示例中,实际上有一些C 继承问题
- 继承问题
- C++继承问题
- C++初学者继承问题
- 公共/受保护/私有继承问题
- 函数继承问题
- 引用类型和继承问题