为了账号安全,请及时绑定邮箱和手机立即绑定

重载朋友操作符<for Template类

重载朋友操作符<for Template类

C++
跃然一笑 2019-06-18 11:21:20
重载朋友操作符<for Template类现在,我在stackoverflow网站上读到了几个关于我的问题,但这些问题似乎都解决不了我的问题。或者我做错了.超载<<如果我把它变成内联函数就行了。但我怎样才能让它在我的案子里起作用呢?warning: friend declaration std::ostream& operator<<(std::ostream&, const D<classT>&)' declares a non-template functionwarning: (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;}
查看完整描述

3 回答

?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

您不能这样声明一个朋友,您需要为它指定一个不同的模板类型。

template <typename SclassT>friend ostream& operator<< (ostream & os, const D<SclassT>& rhs);

SclassT这样它就不会蒙上阴影classT..定义时

template <typename SclassT>ostream& operator<< (ostream & os, const D<SclassT>& rhs){
  // body..}


查看完整回答
反对 回复 2019-06-18
?
胡说叔叔

TA贡献1804条经验 获得超8个赞

在没有任何编译器警告的情况下,这对我有效。

#include <iostream>using namespace std;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 {
    return (d > rhs.d);
  }

  classT operator=(const D<classT>& rhs);

  friend ostream& operator<< (ostream & os, const D& rhs) {
    os << rhs.d;
    return os;
  }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;}


查看完整回答
反对 回复 2019-06-18
  • 3 回答
  • 0 关注
  • 420 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信