我有许多代表各种计算机组件的类,每个类都有一个重载的<<运算符,声明如下:
friend ostream& operator << (ostream& os, const MotherBoard& mb);
Run Code Online (Sandbox Code Playgroud)
每个都返回一个ostream对象,该对象具有描述该组件的唯一流,其中一些组件由其他组件组成.我决定创建一个被调用的基类Component,以便生成一个唯一的id以及所有组件将公开派生的一些其他函数.当然,重载的<<运算符不适用于指向Component对象的指针.
我想知道我将如何影响纯粹的虚函数,这些函数将被每个派生类的<<运算符覆盖,所以我可以做类似的事情:
Component* mobo = new MotherBoard();
cout << *mobo << endl;
delete mobo;
Run Code Online (Sandbox Code Playgroud)
还涉及:重载<<运算符和继承类
也许是这样的:
#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;
}
Run Code Online (Sandbox Code Playgroud)