重载朋友操作符<for Template类

重载朋友操作符<for Template类

现在,我在stackoverflow网站上读到了几个关于我的问题,但这些问题似乎都解决不了我的问题。或者我做错了.超载<<如果我把它变成内联函数就行了。但我怎样才能让它在我的案子里起作用呢?

warning: friend declaration std::ostream& operator<<(std::ostream&, const D<classT>&)' declares a non-template function

warning: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) -Wno-non-template-friend disables this warning

/tmp/cc6VTWdv.o:uppgift4.cc:(.text+0x180): undefined reference to operator<<(std::basic_ostream<char, std::char_traits<char> >&, D<int> const&)'  collect2: ld returned 1 exit status

守则:

template <class T>T my_max(T a, T b){
   if(a > b)      
      return a;
   else
      return b;}template <class classT>class D{public:
   D(classT in)
      : d(in) {};
   bool operator>(const D& rhs) const;
   classT operator=(const D<classT>& rhs);

   friend ostream& operator<< (ostream & os, const D<classT>& rhs);private:
   classT d;};int main(){

   int i1 = 1;
   int i2 = 2;
   D<int> d1(i1);
   D<int> d2(i2);

   cout << my_max(d1,d2) << endl;
   return 0;}template <class classT>ostream& operator<<(ostream &os, const D<classT>& rhs){
   os << rhs.d;
   return os;}


跃然一笑
浏览 421回答 3
3回答

蝴蝶不菲

您不能这样声明一个朋友,您需要为它指定一个不同的模板类型。template&nbsp;<typename&nbsp;SclassT>friend&nbsp;ostream&&nbsp;operator<<&nbsp;(ostream&nbsp;&&nbsp;os,&nbsp;const&nbsp;D<SclassT>&&nbsp;rhs);注SclassT这样它就不会蒙上阴影classT..定义时template&nbsp;<typename&nbsp;SclassT>ostream&&nbsp;operator<<&nbsp;(ostream&nbsp;&&nbsp;os,&nbsp;const&nbsp;D<SclassT>&&nbsp;rhs){ &nbsp;&nbsp;//&nbsp;body..}

胡说叔叔

在没有任何编译器警告的情况下,这对我有效。#include&nbsp;<iostream>using&nbsp;namespace&nbsp;std;template&nbsp;<class&nbsp;T>T&nbsp;my_max(T&nbsp;a,&nbsp;T&nbsp;b){ &nbsp;&nbsp;if(a&nbsp;>&nbsp;b) &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;a; &nbsp;&nbsp;else &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;b;}template&nbsp;<class&nbsp;classT>class&nbsp;D{public: &nbsp;&nbsp;D(classT&nbsp;in) &nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;d(in)&nbsp;{}; &nbsp;&nbsp;bool&nbsp;operator>(const&nbsp;D&&nbsp;rhs)&nbsp;const&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;(d&nbsp;>&nbsp;rhs.d); &nbsp;&nbsp;} &nbsp;&nbsp;classT&nbsp;operator=(const&nbsp;D<classT>&&nbsp;rhs); &nbsp;&nbsp;friend&nbsp;ostream&&nbsp;operator<<&nbsp;(ostream&nbsp;&&nbsp;os,&nbsp;const&nbsp;D&&nbsp;rhs)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;os&nbsp;<<&nbsp;rhs.d; &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;os; &nbsp;&nbsp;}private: &nbsp;&nbsp;classT&nbsp;d;};int&nbsp;main(){ &nbsp;&nbsp;int&nbsp;i1&nbsp;=&nbsp;1; &nbsp;&nbsp;int&nbsp;i2&nbsp;=&nbsp;2; &nbsp;&nbsp;D<int>&nbsp;d1(i1); &nbsp;&nbsp;D<int>&nbsp;d2(i2); &nbsp;&nbsp;cout&nbsp;<<&nbsp;my_max(d1,d2)&nbsp;<<&nbsp;endl; &nbsp;&nbsp;return&nbsp;0;}
打开App,查看更多内容
随时随地看视频慕课网APP