2012-09-30 100 views
0

我有一個GolfCourse類頭gCourse.hh,我想爲>>運算符實現運算符重載。我如何在文件gcourse.cc的標題之外進行此操作?也就是說,我需要指出哪些「詞」本身,「GolfCourse ::」是不夠的,像功能...?在C++中實現運算符在類頭之外的超載

gcourse.hh: 
class GolfCourse { 

public: 
--- 
friend std::istream& operator>> (std::istream& in, GolfCourse& course); 

gcourse.cc: 
---implement operator>> here --- 

回答

2

GolfCourse::不正確,因爲operator >>不是GolfCourse成員。這是一個免費的功能。你只需要寫:

std::istream& operator>> (std::istream& in, GolfCourse& course) 
{ 
    //... 
    return in; 
} 

friend聲明在類定義時,才需要,如果你打算從GolfCourse訪問privateprotected成員。當然,您可以在類定義中提供實現:

class GolfCourse { 
public: 
    friend std::istream& operator>> (std::istream& in, GolfCourse& course) 
    { 
     //... 
     return in; 
    } 
}; 
+0

好吧,現在我可以看到,我只是太執着於功能...謝謝! – rize

+0

是的,我需要訪問GolfCourse的私人成員,所以需要朋友。 – rize