我有许多代表各种计算机组件的类,每个类都有一个重载的 <<
运算符声明如下:
friend ostream& operator << (ostream& os, const MotherBoard& mb);
每个都返回一个 ostream 对象,该对象具有描述该组件的唯一流,其中一些组件由其他组件组成。我决定创建一个名为 Component
的基类为了生成一个唯一的 id 以及所有组件将公开派生的一些其他功能。当然,重载<<
运算符不适用于指向 Component
的指针对象。
我想知道如何实现纯虚函数之类的东西,它会被每个派生类的 <<
覆盖。运算符所以我可以做类似的事情:
Component* mobo = new MotherBoard();
cout << *mobo << endl;
delete mobo;
最佳答案
也许是这样的:
#include <iostream>
class Component
{
public:
// Constructor, destructor and other stuff
virtual std::ostream &output(std::ostream &os) const
{ os << "Generic component\n"; return os; }
};
class MotherBoard : public Component
{
public:
// Constructor, destructor and other stuff
virtual std::ostream &output(std::ostream &os) const
{ os << "Motherboard\n"; return os; }
};
std::ostream &operator<<(std::ostream &os, const Component &component)
{
return component.output(os);
}
int main()
{
MotherBoard mb;
Component &component = mb;
std::cout << component;
}
关于c++ - 基类中的重载输出运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9228173/