函数从子类返回指向父类的指针

时间:2021-04-11 20:41:54

标签: c++ class inheritance virtual-functions

我有这个问题,但我无法解决。我只知道 InitData 函数是 100% 正确的。但是,我试图找到如何创建我的类以使此代码工作(不对 InitData 函数进行任何更改)

class Bird
{
public:
    int data[10];
    int color;

    Bird() {
        ZeroMemory(data, 10 * 4);
        color = 0;
    }

    Bird(int* _data, int _color) {
        memcpy(data, _data, 10 * 4);
        color = _color;
    }

    //more code

};

class Animal : Bird
{
public:
    int data[10];

    Animal() {
        ZeroMemory(data, 10 * 4);
    }

    Animal(int* _data) {
        memcpy(data, _data, 10 * 4);
    }

    //more code

};

Animal* InitData(int* _data, bool isBird) {

    if (isBird) {
        Bird* bird = new Bird(_data, 0);
        return bird;
    }
    else {
        Animal* animal = new Animal(_data);
        return animal;
    }

    return nullptr;
}

也许对虚拟课程做了些什么?

编译器给我错误“E0120 返回值类型与函数类型不匹配”,在 InitData 中的这一行“返回鸟;”。 我使用 Visual Studio 2019,Release(x64),C++17

已解决: 所以我继承了错误的类。需要继承动物到鸟。所以需要改变 “类鸟”到“类鸟:公共动物” 和“类动物:鸟”到“类动物”

谢谢大家!

1 个答案:

答案 0 :(得分:1)

您的继承方式是错误的。 此外,您不需要复制派生类中的数据,因为这是基类的用途,因此您应该调用适当的构造函数,而不是从基类复制代码。

class Animal
{
public:
    int data[10];

    Animal()
    {
        ZeroMemory(data, sizeof(int)*10);
    }

    Animal(int* _data)
    {
        memcpy(data, _data, 10 * sizeof(int));
    }

    //more code
};

class Bird : public Animal
{
public:
    int color;

    Bird()
    {
        color = 0;
    }

    Bird(int* _data, int _color)
    : Animal(_data)
    {
        color = _color;
    }

    //more code

};
相关问题