C++双指针多态性

c++ double pointer polymorphism

我正在尝试使用多态性创建一个指针数组。我将使超类的数组指向多个子类。无论如何这样做并且仍然使用子类中的方法吗?这是示例代码:

#include <iostream>


class Test1
{
public:
    Test1()
        : x(1)
    {}
    int get_x()
    {
        return x;
    }
private:
    int x;
};

class Test2 : public Test1
{
public:
    Test2()
        : y(2)
    {}
    void print()
    {
        std::cout << get_x() << ' ' << y << std::endl;
    }
private:
    int y;
};

class Test3 : public Test1
{
public:
    Test3()
        : y(3)
    {}
    void print()
    {
        std::cout << get_x() << ' ' << y << std::endl;
    }
private:
    int y;
};

int main()
{
    Test1** test = new Test1*[2];
    for (int i = 0; i < 2; i++)
    {
        if (i % 2 == 0)
        {
            test[i] = NULL;
            test[i] = new Test2;
        }
        else
        {
            test[i] = NULL;
            test[i] = new Test3;
        }
    }

    test[0]->print(); // ERROR. Is this even possible?
    test[1]->print(); // ERROR. Is this even possible?


    return 0;
}

谢谢,我只写了大约 8 个月的代码。

如果Test1有这样一个名为print的成员函数就好了。您的代码无法按原样编译,因为 Test::print 不存在。所以至少,您必须定义该成员函数。为了使它成为真正的多态,正如问题的意图所暗示的那样,您应该使 Test::print 成为 virtual 成员函数,以便 Test2Test3 的实现该函数将被调用:

class Test1 { 
    ...
    virtual void print() {
        std::cout << "Test1" << std::endl;
    }
    ...
};

有关详细信息,请参阅有关虚拟功能的this tutorial

test[0]->print(); // ERROR. Is this even possible?

总的来说,是的。但是,不是你的代码。

  1. 如果 Test1 将成为您的基础 class 而您将使用 new 那么它 必须 有一个虚拟析构函数(例如 virtual ~Test1() {}
    • 这是 delete 在通过指向基的指针删除派生类型时正确工作所必需的 class
  2. 您要使用指向基 class 的指针调用的任何函数必须存在于基 class 上(即,您需要 Test1 中的 print 函数)
  3. 如果您希望派生的 classes 有自己的 print 实现,则必须在基础 class 中声明 virtual(例如,virtual void print();)
    • 如果 Test1 实现 print 函数没有意义,那么它可以声明它 纯虚拟 而不是提供一个实现(例如,virtual void print() = 0;)从而使它成为一个抽象 class