C ++从父类型调用子方法而不知道子类型

时间:2018-06-06 15:24:45

标签: c++

我正在尝试将项目从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;
    }

从Component检索ComponentMask枚举值并正确执行按位操作。

C ++的代码片段:

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

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

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

1 个答案:

答案 0 :(得分:0)

OP已经解决了这个问题,所以这是其他任何人遇到这个问题的。

在C ++中,您可以声明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) {}                                          
}
相关问题