C++之派生類的友元
阿新 • • 發佈:2019-01-03
先舉個例子:
#include <iostream>
using namespace std;
class Student{
private:
int _a;
int _b;
public:
Student(int a, int b):_a(a), _b(b){}
friend ostream& operator <<(ostream& os, Student& s){
os << s._a << "--" << s._b;
return os;
}
};
class Graduate: public Student{
private:
int _c;
public:
Graduate(int a, int b, int c):Student(a, b), _c(c){}
};
int main()
{
Student s(1, 2);
cout << s << endl;
Graduate gra(3, 4, 5);
cout << gra << endl;
return 0;
}
輸出結果為:
父類Student有一個輸出流過載,可以看到子類Graduate可以利用隱式轉換成父類Student,並呼叫了父類的友元函式,最終的輸出格式跟父類一樣。那如果子類想輸出從父類繼承的東西還有自己的東西,就得過載operator<<這個全域性函式:
#include <iostream>
using namespace std;
class Student{
private:
int _a;
int _b;
public:
Student(int a, int b):_a(a), _b(b){}
friend ostream& operator <<(ostream& os, Student& s){
os << s._a << "--" << s._b;
return os;
}
};
class Graduate: public Student{
private:
int _c;
public:
Graduate(int a, int b, int c):Student(a, b), _c(c){}
friend ostream& operator<<(ostream& os, Graduate& gra){
cout << static_cast<Student&>(gra);
os << "--" << gra._c;
return os;
}
};
int main()
{
Student s(1, 2);
cout << s << endl;
Graduate gra(3, 4, 5);
cout << gra << endl;
return 0;
}
輸出結果為:
這裡只需要注意過載的函式裡內,需要先將子類顯示的轉換成父類的引用(以為轉換過程中會形成中間變數,而這個中間變數是個臨時值,所以必須用引用來接收,或者將父類友元的引數型別改成:const Student& ),去呼叫父類的友元,因為子類不能直接訪問父類的私有成員,最後再輸出自己的東西就可以了。