【问题标题】:Overloading the << operator error C2804: binary 'operator <<' has too many parameters重载<<操作符错误C2804:二进制'操作符<<'有太多参数
【发布时间】:2013-03-24 13:32:02
【问题描述】:

这是我的课:

#ifndef CLOCK_H
#define CLOCK_H
using namespace std;

class Clock
{
    //Member Variables

    private: int hours, minutes;

    void fixTime( );

    public:
        //Getter & settor methods.
        void setHours(int hrs); 
        int getHours() const;
        void setMinutes(int mins); 
        int getMinutes() const; 

        //Constructors
        Clock(); 
        Clock(int);
        Clock(int, int);
        //Copy Constructor
        Clock(const Clock &obj);
        //Overloaded operator functions
        void operator+(const Clock &hours);
        void operator+(int mins);
        void operator-(const Clock &hours);
        void operator-(int minutes1);
        ostream &operator<<(ostream &out, Clock &clockObj); //This however is my problem where i get the error C2804. Saying that it has to many parameters 
};
#endif

这个函数应该做的就是输出不同时间的时钟值。

【问题讨论】:

  • 它有三个参数。它应该有两个。
  • 为了将来参考,请不要在发布代码块时使用代码高亮反引号。有一个单独的按钮(或者您只需将每行缩进 4 个空格。

标签: c++ class operator-overloading


【解决方案1】:
ostream &operator<<(ostream &out, Clock &clockObj); 

应该是

friend ostream &operator<<(ostream& out, Clock &clockObj);    

在类之外定义。

请看这里:Should operator<< be implemented as a friend or as a member function?

【讨论】:

  • 大部分是对的,但它没有必须在类之外定义。
【解决方案2】:
 ostream &operator<<(ostream &out, Clock &clockObj);

应该是

 friend ostream &operator<<(ostream &out, Clock &clockObj);

根据 Stanley 等人的 C++ Primer (Fourth Edition pp 514):

当我们定义一个符合 iostream 库的约定,我们必须使其成为非成员 操作员。我们不能让操作符成为我们自己类的成员。要是我们 做了,那么左边的操作数必须是我们的对象 班级类型

因此,最好将&lt;&lt;&gt;&gt; 重载为类的友元函数。

【讨论】:

  • 哇.. 非常感谢。我可能看起来真的很愚蠢。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-02
  • 1970-01-01
  • 2022-11-04
  • 2012-01-24
  • 1970-01-01
  • 2016-06-26
相关资源
最近更新 更多