【发布时间】:2015-04-18 03:46:32
【问题描述】:
我正在尝试使用多态性创建一个指针数组。我会让超类的数组指向多个子类。有没有这样做并且仍然使用子类中的方法?这是一个示例代码:
#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 个月。
【问题讨论】:
-
你会想要阅读virtual functions。
标签: c++ pointers polymorphism