c++ - vect.hpp:13:33:错误: ‘operator<<’声明为无效

标签 c++ templates friend

我有这个错误

vect.hpp:13:33: error: declaration of ‘operator<<’ as non-function



对于代码:
#include <iostream>

template<unsigned d>
class Vect{
    protected:
        double * coord;
    public:
        Vect() {for(int i=0, i<d, i++){*(coord+i)=0;}}
        ~Vect(){delete coord; coord=nullptr;}
        Vect(const Vect &);
        double operator=(const Vect &);
        double operator[](unsigned i) const{return *(coord+i);}
        friend std::ostream & operator<< <>(std::ostream &, const Vect<d> &); 
};

对于该行:
friend std::ostream & operator<< <>(std::ostream &, const Vect<d> &); 

最佳答案

friend 声明是指operator<<的实例化,但没有主模板声明。您需要提前声明运算符(operator)模板。例如

// forward declaration
template<unsigned d>
class Vect;

// primary template declaration of operator<<
template<unsigned d>
std::ostream & operator<< (std::ostream &, const Vect<d> &); 

template<unsigned d>
class Vect{
    protected:
        double * coord;
    public:
        Vect() {for(int i=0; i<d; i++){*(coord+i)=0;}}
        ~Vect(){delete coord; coord=nullptr;}
        Vect(const Vect &);
        double operator=(const Vect &);
        double operator[](unsigned i) const{return *(coord+i);}
        friend std::ostream & operator<< <>(std::ostream &, const Vect<d> &); 
};

LIVE

关于c++ - vect.hpp:13:33:错误: ‘operator<<’声明为无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61672608/

相关文章:

c++ - CUDA 共享内存的可能性

c++ - 素数的 bool 函数

c++ - 为什么不能在函数中声明模板?

C++ 模板友元运算符重载

c++ - 当类和函数具有单独的模板参数时,在类定义之外定义友元函数

c++ - 具有不同模板参数的相同类不能访问彼此的私有(private)字段

c++ - 如何比较两个不同文本文件中的两个不同字符串?

c++ - 从自定义数据类型列表中删除时出现 C2678 错误

c++ - 回归虚无?

c++ - 从成员函数模板化参数调用成员函数