8

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

我的头文件

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& operator<<(std::ostream&, const Vector&)' 声明一个非模板函数|

C:\CodeBlocks\kool\praks3\vector.h|14|注意:(如果这不是您想要的,请确保函数模板已经声明并在此处的函数名称后添加<>)|

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

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

4

2 回答 2

11

请看错误,它说,

友元声明 'std::ostream& operator<<(std::ostream&, const Vector&)' 声明一个非模板 函数|

这意味着您需要制作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;
}
于 2011-03-12T18:20:37.490 回答
7

只需在类中定义朋友函数。

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

于 2011-03-12T18:35:17.740 回答