C++ 在不知道子类型的情况下从父类型调用子方法
C++ Calling child method from parent type without knowing child type
我正在尝试将项目从 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) {}
}
相关文章:
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- 调用具有未标识类型的类的方法
- 在运行时选择父类的实现
- C++ 中模板化类型的类层次结构
- 如何在C++子类中访问父类的私有变量
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 当函数返回类型为父类时,如何返回子类的对象?
- C 不能将带有父类指针作为类型的静态模板成员定义引用
- 比较从父类继承但存储在父类的向量中的类的对象类型
- 当父类共享指针为返回类型时返回新的基类
- 我能判断投射到父类中的对象类型最初是否是C++中的子类吗
- 在C++中将派生类类型的向量链接到父类类型的向量
- 在类中声明与父类具有相同类型的模板类
- c++中的多态性,父类的载体中的类型丢失
- 如何调用父类类型列表的子类的方法?C++
- 如何使用父类类型的智能指针调用子类的析构函数
- 将父类类型的成员驻留在另一个类中