【发布时间】:2011-06-07 07:17:15
【问题描述】:
我现在已经在 StackOverflow.com 上阅读了几个关于我的问题的问题,但似乎都没有解决我的问题。或者我可能做错了......
如果我将重载的<< 做成内联函数,它就可以工作。但是我该如何让它在我的情况下发挥作用呢?
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;
}
【问题讨论】:
-
最近有一个关于这个的问题可能很有启发性:stackoverflow.com/questions/4571611/virtual-operator
-
@Daniel - 它不会解决我在为模板类重载时遇到的问题
-
我认为最好不要用给定的答案修改问题。这使得更难确定最初的问题是什么。您可能希望在末尾添加 EDIT 并添加 解决 问题的更改,但是当问题超时更改时我发现它很混乱,我必须将历史记录拉到首先看看实际被问到了什么。
标签: c++ templates operator-overloading friend ostream