在C++中使用克隆方法实现多晶型效果



我在最后一个问题中完全不清楚另一个主题(使其成为XY问题(,所以我将从基础知识开始。 我在课堂上有一个名为列表的列表

class List {
private:
struct Elem {
Notification* notif;
Elem* next;
Elem(const Notification& OB) : notif(OB.clone()), next(nullptr) {}
};
Elem* first; };
I have a class Notification 
class Notification {
public:
virtual Notification* clone() const { return new Notification(*this); }
virtual write(ostream& os)const { return os << "Some text from class Notif";}
friend ostream& operator<<(ostream& os, const Notification& OB) {
OB.write(os); return os; } };

我还有一个从通知派生的类错误,应该具有不同定义的运算符<<

class Error: public Notification {
private:
string error_text;
public:
Error* clone() const { return new Error(*this); }
friend ostream& operator<<(ostream& os, Error& OBJ) {
OBJ.Notification::write(os); os << OBJ.error_text << endl;
return os;
}
};

现在我想通过覆盖运算符<<将列表打印到输出

ostream& operator<<(ostream& os, const List& list) {
List::Elem* new = list.first;
while (new) {
os << *(new->notification);
new = new->next;
}
return os;
}

但是当我在主要cout << list时,我只收到通知消息。有没有办法绕过运算符<<成为全局朋友函数?多态性不起作用是因为它是一个全局函数还是因为我在打印时取消引用指针?我已经有点迷茫了..

编辑- 已解决

我欠1201ProgramAlarm道歉。

我需要覆盖 write((,但问题是 write 不需要返回 os,因为 os 是通过引用传递的,write(( 实际上应该返回 void。也无需再次覆盖运算符<<。我可以覆盖方法write((。通过覆盖 write((,我更改了调用 os <<*(新>通知(时将要调用的方法;在列表中,这正是我想做的

我欠1201ProgramAlarm道歉。

我需要覆盖write()但问题是 write 不需要返回os因为os是通过引用传递的,write()实际上应该返回 void。也没有必要再次覆盖operator<<。我可以覆盖方法write().通过覆盖write()我更改了在 List 中调用os << *(new->notification);时将要调用的方法,这正是我想要做的。

最新更新