C++ 在不知道子类型的情况下从父类型调用子方法

C++ Calling child method from parent type without knowing child type

本文关键字:类型 父类 调用 子方法 情况下 不知道 C++      更新时间:2023-10-16

我正在尝试将项目从 c# 转换为 c++,并遇到了一个我不确定如何在 c++ 中实现的功能。

我有一个对象列表(或向量(,所有对象都强制转换为其父类型。在 c# 中,我可以在不知道子函数的情况下从此列表中的对象调用函数,并且将调用相应的子函数,但是我不确定如何使此特定功能在 c++ 中工作。

来自 C# 的代码片段:

public void AddComponent(IComponent component)
{
Debug.Assert(component != null, "Component must not be null");
componentList.Add(component);
mask |= component.ComponentMask;
}

从组件中检索组件掩码枚举值并正确执行按位运算。

来自C++的代码片段:

void oEntity::AddComponent(IComponent &componentIn)
{
componentList.push_back(componentIn);
mask |= componentIn.ComponentMask();
}

这将返回错误"IComponent 无法实例化抽象类",如果我从方法中删除括号,运算符重载不再工作并抛出错误"二进制'|=':未找到采用类型为"重载函数"的右操作数的运算符(或者没有可接受的转换(">

掩码值是一个枚举,其中包含用作标识组件类型的标志的位移整数。运算符也已适当重载以使用枚举类型。

OP 已经想通了,所以这是给遇到这个问题的其他人的。

在C++中,你可以声明virtual方法(你也可以声明虚拟方法,但这有点复杂(。这些方法可以被子类覆盖,但也必须自己实现,否则你会得到一些神秘的错误。

如果希望它们在默认情况下不执行任何操作,最简单的解决方案是仅使用空主体定义它们。下面是一个简单的示例:

class ParentClass
{
int x, y;
virtual void handleNewPos(int newX, int newY){}
public:
ParentClass(int x, int y)
{
resetPos(x, y);
}
void resetPos(int newX, int newY)
{
handleNewPos(newX, newY);
x = newX;
y = newY;
}
}
class ChildClass: public ParentClass
{
// marked 'override' because it's replacing a previous virtual method that had the same
// return type / params. Not required, but if you're using C++11 or greater, than it's
// preferred 
virtual void handleNewPos(int newX, int newY) override
{
// Every time the resetPos method is called, it prints out it's new position.
std::cout << "New Position: " << newX << ", " << newY << std::endl;
}      
public:
ChildClass(int x, int y): ParentClass(x, y) {}                                          
}