C ++模板/OStream运算符问题 [英] C++ template/ostream operator question

查看:135
本文介绍了C ++模板/OStream运算符问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图让操作员正常工作,但给我带来了很多错误:

trying to get the operator to work, but throwing me bunch of errors:

我的头文件

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

C:\CodeBlocks\kool\praks3\vector.h|14|warning: friend declaration 'std::ostream& operator<<(std::ostream&, const Vector&)' declares a non-template function|

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

C:\CodeBlocks\kool\praks3\vector.h|14|note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) |

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

obj\Debug\test.o||In function `main':|

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

C:\CodeBlocks\kool\praks3\test.cpp|8|undefined reference to `operator<<(std::ostream&, Vector<(unsigned short)3> const&)'|

推荐答案

请查看错误提示,

朋友声明'std :: ostream& 运算符<((std :: ostream& ;, const Vector&)'声明非模板 功能|

friend declaration 'std::ostream& operator<<(std::ostream&, const Vector&)' declares a non-template function|

这意味着您需要将operator<<用作模板函数.

That means you need to make the operator<< a template function.

因此,在该类中,您必须将其声明为:

So in the class, you've to declare it as:

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;
}

这篇关于C ++模板/OStream运算符问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆