gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:47:24 25 4
gpt4 key购买 nike

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

我有一个对象列表(或 vector ),所有对象都转换为它们的父类型。在 c# 中,我可以在不知道子对象的情况下从该列表中的对象调用函数,并且将调用适当的子函数,但是我不确定如何使这个特定功能在 c++ 中工作。

来自 C# 的代码片段:

        public void AddComponent(IComponent component)
{
Debug.Assert(component != null, "Component must not be null");

componentList.Add(component);
mask |= component.ComponentMask;
}

从 Component 中检索 ComponentMask 枚举值并正确执行按位运算。

C++ 代码片段:

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

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

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

最佳答案

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

在 C++ 中,您可以声明 virtual 方法(您也可以声明 pure virtual 方法,但这有点复杂)。这些方法可以被子类覆盖,但也必须自己实现,否则你会得到一些cryptic errors。 .

如果您希望它们默认不执行任何操作,最简单的解决方案是只用空主体定义它们。这是一个简单的例子:

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++在不知道子类型的情况下从父类型调用子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50724105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com