sacredseven,华硕贝壳机,自从你走后 胡东
template<typename> class d;//因为友元函数的参数里使用了d,所以要先在这里声明一下 template<typename t> ostream& operator<< (ostream&, const d<t> &);
//注意operator<<后面有<t> friend ostream& operator<< <t>(ostream& ,const d<t>&);
template<typename t> //注意operator<<后面没有<t> ostream& operator << (ostream& out,const d<t>& d){ out << d.x; return out; }
例子代码:
#include <iostream> using namespace std; template<typename t> class test{ public: test(t t) : data(t){} virtual void show() = 0; private: t data; }; template<typename> class d; template<typename t> ostream& operator<< (ostream&, const d<t> &); template<typename t> class d : public test<t>{ //注意有<t> friend ostream& operator<< <t>(ostream& ,const d<t>&); public: //注意不是test(t1) d(t t1, t t2) : test<t>(t1), x(t2){} void show(){ cout << x << ", " << x << endl; } private: t x; }; template<typename t> ostream& operator << (ostream& out,const d<t>& d){ out << d.x; return out; } int main(void){ test<int> *p = new d<int>(10, 21); p->show(); d<int> d(10,20); cout << d << endl; return 0; }
下面的例子没有什么实际意义,只看语法。
#include <iostream> using namespace std; class foo{ public: foo(int a, int b, int c) : x(a), y(b), z(c){} void show(){ cout << x << "," << y << "," << z << endl; } private: int x, y, z; }; template <typename t> class goo : public foo{ public: goo(t t, int a, int b, int c):foo(a,b,c), data(t){} void show(){ cout << data << endl; cout << "goo show" << endl; } private: t data; }; class hoo : public goo<int>{ public: hoo(int a1,int a2,int a3,int a4,int a5): goo(a1,a2,a3,a4),ho(a5){} void show(){ cout << "hoo show" << endl; } private: int ho; }; int main(void){ hoo hoo(1,2,3,4,5); hoo.show(); goo<string> goo("abc",1,2,3); goo.show(); return 0; }
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
如何在没有core文件的情况下用dmesg+addr2line定位段错误
用QT制作3D点云显示器——QtDataVisualization
网友评论