几个关键点:
需要前置声明!--奇怪的是别人告诉我也可以不需要,但我这里不行!
友元函数的函数名后面的<>,必须要有。
#include <stdio.h> #include <iostream> using namespace std; //前置声明,你妹啊 template<class T> class A; template<class T> ostream &operator<< (ostream &out, const A<T> &_a); template<class T1, class T2> class B; template<class T1, class T2> ostream &operator<< (ostream &out, const B<T1, T2> &_b); template<class T> class A { public: A(){} A(T _a, T _b):a(_a),b(_b){} ~A(){} private: T a; T b; friend ostream &operator<< <> (ostream &out, const A<T> &a); }; template<class T> ostream &operator<< (ostream &out, const A<T> &_a){ out<<_a.a<<"--"<<_a.b; return out; } template<class T1, class T2> class B: public A<T1> { public: B(){} B(T1 _a, T1 _b, T2 _c):A<T1>(_a,_b),c(_c){} //A<T1> ~B(){} private: T2 c; friend ostream &operator<< <>(ostream &out, const B<T1, T2> &_b); }; template<class T1, class T2> ostream &operator<< (ostream &out, const B<T1, T2> &_b){ // out<<(A<T1>)_b; // out<<"--"<<_b.c; out<<(A<T1>)_b<<"--"<<_b.c; return out; } int main(int argc, char const *argv[]) { A<int> x(1, 3); B<char, int> y(‘a‘, ‘b‘, 5); cout<< x <<endl; cout<< y <<endl; return 0; }
时间: 2024-10-24 03:48:48