【发布时间】:2015-07-28 13:51:45
【问题描述】:
我有以下问题。
我已经创建了一个指向基类对象的指针数组,但是我在这个数组中还存储了指向派生类对象的指针。
我还在每个类中重载了<<operator 以显示对象。
但是,当我将这个重载的<<operator 应用到上述数组时,它会将所有指针视为指向基类的对象。
下面我给出了描述问题的代码。 我需要这个重载的运算符才能正常工作,因为我需要将数组指向的对象保存在文件中。
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
class Base
{
public:
int basevar;
Base(): basevar(1) {};
virtual void dosth(){};
friend ostream & operator<<(ostream & screen, const Base & obj);
};
ostream & operator<<(ostream & screen, const Base & obj)
{
screen << obj.basevar;
return screen;
};
class Der1: public Base
{
public:
int de1;
Der1(): de1(2) {};
virtual void dosth()
{
cout << "Der1" << endl;
}
friend ostream & operator<<(ostream & screen, const Der1 & obj);
};
ostream & operator<<(ostream & screen, const Der1 & obj)
{
Base b;
b = static_cast <Base>(obj);
screen << b;
screen << " " << obj.de1;
return screen;
};
class Der2: public Base
{
public:
int de2;
Der2(): de2(3) {};
virtual void dosth()
{
cout << "Der2" << endl;
}
friend ostream & operator<<(ostream & screen, const Der2 & obj);
};
ostream & operator<<(ostream & screen, const Der2 & obj)
{
Base b;
b = static_cast <Base>(obj);
screen << b;
screen << " " << obj.de2;
return screen;
}
int main()
{
Base * array[] = {new Base(), new Der1(), new Der2()};
for(int i=0; i<3; ++i)
{
cout << *array[i]; // <- always displays objects as if they were from the base class
}
return 0;
}
【问题讨论】: