類里面重載運算符>>, 需要使用友元函數,而友元函數,不能作為虛函數。
所以,基類指針無法直接調用繼承類里重構的 >> ;
使用類轉換,能解決掉,基類指針 調用 繼承類 函數的問題。
#include<iostream> #include<math.h> #include<string> using namespace std; class Person{ string a, b; public: virtual void show(){cout<<a<<" "<<b<<" ";} friend istream &operator >>(istream&in, Person&d){in>>d.a>>d.b;cout<<555;return in;};//輸入兩個數 }; class Gun: public Person{ double gu; public: friend istream &operator >>(istream&in,Gun&d){ in>>d.gu;cout<<111;return in;}//輸入一個數 void show(){Person::show();cout<<gu<<endl;} }; int main(){ Person*g; g=new Gun; cin>>(*(Gun*)g); Person*gg; gg=new Gun; cin>>*gg; }
繼承類調用基類友元函數 如 >> 只能用顯示轉換
class Person{
public: string a, b;
friend istream &operator >>(istream&in, Person&d){in>>d.a>>d.b;return in;}
};
class Gun: public Person{
double gu;
public:
friend istream &operator >>(istream&in,Gun&d){ in>>(Person&)d;in>>d.gu;return in;}
};