2013-11-23 64 views
1

我已经定义了一个使用dev C++的点类。然后我试图为这个班级重载cout。 虽然没有使用它,我没有得到任何错误。但是当我在主要使用它,它给了我这个错误:undefined引用,而重载cout

[Linker error] C:\Users\Mohammad\Desktop\AP-New folder\point/main.cpp:12: undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Point const&)' 

//point.h

class Point{ 
private: 
    double x; 
    double y; 
    double z; 
public: 

    //constructors: 
    Point() 
    { 
    x=0; 
    y=0; 
    z=0; 
    } 
    Point(double xx,double yy,double zz){x=xx; y=yy; z=zz;} 

    //get: 
    double get_x(){return x;} 
    double get_y(){return y;}  
    double get_z(){return z;} 

    //set: 
    void set_point(double xx, double yy, double zz){x=xx; y=yy; z=zz;} 

    friend ostream &operator<<(ostream&,Point&); 

};

//point.cpp 
    ostream &operator<<(ostream &out,Point &p){ 
     out<<"("<<p.x<<", "<<p.y<<", "<<p.z<<")\n"; 
     return out; 

}

//main.cpp

#include <iostream> 
    #include "point.h" 

    using namespace std; 

    int main(){ 

Point O; 
cout<<"O"<<O; 


cin.get(); 
return 0; 

}

回答

2

这是因为你没有让你的Point声明和定义您的操作时,const。改变你的声明如下:

friend ostream &operator<<(ostream&, const Point&); 

的定义也添加const

ostream &operator<<(ostream &out, const Point &p){ 
    out<<"("<<p.x<<", "<<p.y<<", "<<p.z<<")\n"; 
    return out; 
} 

请注意,您发布的代码不需要const -ness的Point&的。一些其他代码使您的编译器或IDE相信引用了const的运算符。例如,使用操作员等,这将需要一个const

cout << Point(1.2, 3.4, 5.6) << endl; 

(demo)

由于上面的代码段创建一个临时对象,传递一个参考到它作为一个非const由C++标准禁止。

没有直接关系这一问题,但你可能要标注为各个坐标三个干将const还有:

double get_x() const {return x;} 
double get_y() const {return y;}  
double get_z() const {return z;} 

这将允许您访问的坐标与对象的getter标const

+0

它似乎是答案 –

+0

但在learncpp.com它没有使用const! –

+0

http://www.learncpp.com/cpp-tutorial/93-overloading-the-io-operators/ –