gpt4 book ai didi

c++ - 指向包含派生类对象和重载 << 运算符的基类的指针数组

转载 作者:行者123 更新时间:2023-11-30 02:38:58 25 4
gpt4 key购买 nike

我有以下问题。

我创建了一个指向基类对象的指针数组,但我也在这个数组中存储了指向派生类对象的指针。

我还重载了 <<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;
}

最佳答案

可以通过以下方式在基类中声明一个虚函数

class Base
{
public:
int basevar;
Base(): basevar(1) {};
virtual std::ostream & out( std::ostream &os ) const
{
return os << basevar;
}

virtual void dosth(){};
friend ostream & operator<<(ostream & screen, const Base & obj);
};

在这种情况下,运算符看起来像

ostream & operator<<(ostream & screen, const Base & obj)
{
return obj.out( screen );
};

并在派生类中重新定义虚函数。例如

class Der1: public Base
{
public:
int de1;
Der1(): de1(2) {};
std::ostream & out( std::ostream &os ) const
{
return Base::out( os ) << " " << obj.de1;
}
virtual void dosth()
{
cout << "Der1" << endl;
}
};

在这种情况下,无需为派生类定义运算符。

关于c++ - 指向包含派生类对象和重载 << 运算符的基类的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30279823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com