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

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

我有这个错误

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> &); 

友元声明指的是 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

你也可以在class里面做定义。

#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 &os, const Vect<d> &obj)
        {
          // Your code goes here
        }

};