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

偶尔善良 提交于 2021-01-28 05:31:07

问题


I have this error

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

for the code :

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

for the line :

friend std::ostream & operator<< <>(std::ostream &, const Vect<d> &); 

回答1:


The friend declaration refers to the instantiation of the operator<< but there's no primary template declaration. You need to declare the operator template in advance. e.g.

// 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




回答2:


You can also do do the definition inside the 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
        }

};


来源:https://stackoverflow.com/questions/61672608/vect-hpp1333-error-declaration-of-operator-as-non-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!