2013-11-23 59 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/ –