在C ++中实现类头之外的运算符重载

时间:2012-09-30 17:38:26

标签: c++ class overloading operator-keyword

我有一个GolfCourse类头gcourse.hh,我想为>>运算符实现运算符重载。如何在文件gcourse.cc的标题之外执行此操作?也就是说,我需要将哪些“单词”指向类本身,“GolfCourse ::”对于函数来说还不够......?

gcourse.hh:
class GolfCourse {

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

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

1 个答案:

答案 0 :(得分:2)

GolfCourse::不正确,因为operator >>不是GolfCourse的成员。这是一个免费的功能。你只需要写:

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

只有在您计划从friend访问privateprotected成员时,才需要在课程定义中GolfCourse声明。当然,您可以在类定义中提供实现:

class GolfCourse {
public:
    friend std::istream& operator>> (std::istream& in, GolfCourse& course)
    {
       //...
       return in;
    }
};
相关问题