【问题标题】:Implementing operator overload outside class header in C++在 C++ 中实现类头之外的运算符重载
【发布时间】:2012-09-30 17:38:25
【问题描述】:

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

gcourse.hh:
class GolfCourse {

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

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

【问题讨论】:

    标签: c++ class overloading operator-keyword


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 好的,现在我明白了,我只是太执着于实现功能......谢谢!
    • 是的,我需要访问 GolfCourse 的私人会员,所以需要朋友。
    猜你喜欢
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 2013-11-22
    • 2011-12-04
    相关资源
    最近更新 更多