C ++模板/ ostream运算符问题

时间:2011-03-12 18:18:49

标签: c++ operator-keyword ostream

试图让操作员工作,但却给我一堆错误:

我的头文件

template <unsigned short n>
class Vector {
public:
    std::vector<float> coords;

    Vector();
    Vector(std::vector<float> crds);
    friend std::ostream& operator <<(std::ostream& out, const Vector& v);
};

template <unsigned short n>
Vector<n>::Vector() {
coords.assign(n, 0.0);
}

template <unsigned short n>
std::ostream& operator<<(std::ostream& out, const Vector<n>& v) {
out << "(" << v.coords[1] << " - " << v.coords[2] << ")";
return out;
}

测试文件

#include <iostream>
#include "vector.h"
using namespace std;

int main() {
Vector<3> toomas;
cout << toomas;

}

错误:

C:\ CodeBlocks \ kool \ praks3 \ vector.h | 14 |警告:朋友声明'std :: ostream&amp; operator&lt;&lt;(std :: ostream&amp;,const Vector&amp;)'声明非模板函数|

C:\ CodeBlocks \ kool \ praks3 \ vector.h | 14 |注意:(如果这不是您的意图,请确保已声明函数模板并在此处添加&lt;&gt;之后的函数名称) |

obj \ Debug \ test.o ||在函数`main'中:|

C:\ CodeBlocks \ kool \ praks3 \ test.cpp | 8 |未定义引用`operator&lt;&lt;(std :: ostream&amp;,Vector&lt;(unsigned short)3&gt; const&amp;)'|

2 个答案:

答案 0 :(得分:10)

请查看错误,它说,

  

朋友声明'std :: ostream&amp;   operator&lt;&lt;(std :: ostream&amp;,const   Vector&amp;)'声明非模板   函数|

这意味着您需要使operator<<成为模板函数。

所以在课堂上,你要把它声明为:

template<unsigned short m> //<----note this: i.e make it template!
friend std::ostream& operator <<(std::ostream& out, const Vector<m>& v);

然后将其定义为,

template <unsigned short m>
std::ostream& operator<<(std::ostream& out, const Vector<m>& v) {
   out << "(" << v.coords[1] << " - " << v.coords[2] << ")";
   return out;
}

答案 1 :(得分:5)

只需在类中定义友元函数即可。

template <unsigned short n>
class Vector
{
public:
    std::vector<float> coords;

    Vector();
    Vector(std::vector<float> crds);
    friend std::ostream& operator <<(std::ostream& out, const Vector& v)
    {
        out << "(" << v.coords[1] << " - " << v.coords[2] << ")";
        return out;
    }
};

template <unsigned short n>
Vector<n>::Vector()
{
    coords.assign(n, 0.0);
}


int main()
{
    Vector<3> toomas;
    cout << toomas;
}

经过测试:http://ideone.com/LDAR4

或者,使用前向原型预先声明模板函数:

template <unsigned short n>
class Vector;

template <unsigned short n>
std::ostream& operator <<(std::ostream& out, const Vector<n>& v);

template <unsigned short n>
class Vector
{
public:
    std::vector<float> coords;

    Vector();
    Vector(std::vector<float> crds);
    friend std::ostream& operator << <>(std::ostream& out, const Vector& v);
};

template <unsigned short n>
Vector<n>::Vector()
{
    coords.assign(n, 0.0);
}

template <unsigned short n>
std::ostream& operator <<(std::ostream& out, const Vector<n>& v)
{
    out << "(" << v.coords[1] << " - " << v.coords[2] << ")";
    return out;
}

经过测试:http://ideone.com/8eTeq