我有一些对象(类)都继承自基类Structure。这些对象的打印方式不同,因为它们具有不同的成员变量但共享共同的功能。
我希望能够拥有一个结构列表并打印它们而不必将它们转换回特定对象,即:Structure - >建筑物。
这在C ++中是否可行?
class Structure
{
};
class Building : public Structure
{
public:
friend std::ostream& operator<<(std::ostream& o, const Building &b)
{
return o << b.m_windows.size() << b.m_doors.size();
}
protected:
Windows m_windows;
Doors m_doors;
};
class Statue : public Structure
{
public:
friend std::ostream& operator<<(std::ostream& o, const Statue &s)
{
return o << s.m_type;
}
protected:
StatueType m_type;
};
int main(int argc, char* argv[])
{
Structure struct* = new Building();
std::cout << struct << std::endl;
return 0;
}
Error:
error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
std::cout << struct << std::endl;
修改
我已经在我自己的代码中隔离了这个问题,这是一个可编译的版本(C11)。问题是我正在使用进一步的继承,我的命令输出是:
CORRECT_VALUE<random address>
8.8.8.80x804c504
我不确定为什么会附加那个随机地址?
答案 0 :(得分:5)
创建虚拟输出函数并在operator <<
内调用它。在派生类中重写此输出函数。
class Structure
{
public:
virtual ~Structure() {}
virtual std::ostream& StreamOut(std::ostream& o) const { return o; }
friend std::ostream& operator<<(std::ostream& o, const Structure &s)
{
return s.StreamOut(o);
}
};
class Building : public Structure
{
public:
virtual std::ostream& StreamOut(std::ostream& o) const
{
return o << m_windows.size() << m_doors.size();
}
protected:
Windows m_windows;
Doors m_doors;
};
class Statue : public Structure
{
public:
virtual std::ostream& StreamOut(std::ostream& o) const
{
return o << m_type;
}
protected:
StatueType m_type;
};
int main(int argc, char* argv[])
{
std::unique_ptr<Structure> myStruct(new Building());
std::cout << *myStruct << std::endl;
}