为类重载<<与>>这两个运算符时,重载函数必须为该类的友元函数。
当友元不能被继承,故不能当作虚函数,无法使用多态。
可以用以下结构实现友元与虚函数的组合。
1 class base { 2 public: 3 friend ostream & operator << (ostream &o, const base &b); 4 private: 5 virtual ostream & print(ostream & o) const { 6 return o << "Hello, Base"; 7 } 8 }; 9 10 class derived : public base { 11 public: 12 private: 13 virtual ostream & print(ostream & o) const override { 14 return o << "Hello, Derived"; 15 } 16 }; 17 18 ostream & operator << (ostream &o, const base &b) 19 { 20 return b.print(o); 21 } 22 23 int main() 24 { 25 base base_obj; 26 derived derived_obj; 27 vector<base *> v = {&base_obj, &derived_obj}; 28 for(auto i: v) { 29 cout << *i << endl; 30 } 31 return 0; 32 }
时间: 2024-10-11 03:29:23