c++基類指針指向繼承類調用繼承類函數


 

類里面重載運算符>>, 需要使用友元函數,而友元函數,不能作為虛函數。

所以,基類指針無法直接調用繼承類里重構的 >>  ;

使用類轉換,能解決掉,基類指針 調用 繼承類 函數的問題。

 

 

#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;}

};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM