“friend”函数和 << 运算符重载:为类重载运算符的正确方法是什么?

2023-11-21

在我正在进行的一个项目中,我有一个Score类,定义如下score.h。我试图超载它,所以,当<<对其进行操作,_points + " " + _name被打印。

这是我尝试做的:

ostream & Score::operator<< (ostream & os, Score right)
{
    os << right.getPoints() << " " << right.scoreGetName();
    return os;
}

以下是返回的错误:

score.h(30) : error C2804: binary 'operator <<' has too many parameters

(这个错误实际上出现了4次)

我设法通过将重载声明为友元函数来使其工作:

friend ostream & operator<< (ostream & os, Score right);

并删除Score::来自score.cpp 中的函数声明(实际上没有将其声明为成员)。

为什么这行得通,而前一段代码却行不通?

谢谢你的时间!

EDIT

我删除了头文件中所有关于重载的内容...但我收到以下(也是唯一的)错误。binary '<<' : no operator found which takes a right-hand operand of type 'Score' (or there is no acceptable conversion)为什么我的测试在 main() 中找不到合适的重载? (这不是包含,我检查过)

以下是满分.h

#ifndef SCORE_H_
#define SCORE_H_

#include <string>
#include <iostream>
#include <iostream>

using std::string;
using std::ostream;

class Score
{

public:
    Score(string name);
    Score();
    virtual ~Score();
    void addPoints(int n);
    string scoreGetName() const;
    int getPoints() const;
    void scoreSetName(string name);
    bool operator>(const Score right) const;

private:
    string _name;
    int _points;

};
#endif

Note:您可能想看看运算符重载常见问题解答.


二元运算符可以是其左侧参数的类的成员,也可以是自由函数。 (某些运算符(如赋值)必须是成员。)由于流运算符的左侧参数是流,因此流运算符必须是流类的成员或自由函数。规范的实现方式operator<<对于任何类型都是这样的:

std::ostream& operator<<(std::ostream& os, const T& obj)
{
   // stream obj's data into os
   return os;
}

请注意,它是not成员函数。另请注意,它需要对象按每个流式传输const参考。这是因为您不想复制对象以对其进行流式传输,并且也不希望流式传输更改它。


有时,您想要流式传输其内部无法通过类的公共接口访问的对象,因此操作员无法访问它们。那么你有两个选择:要么将一个公共成员放入进行流式处理的类中

class T {
  public:
    void stream_to(std::ostream&) const {os << obj.data_;}
  private:
    int data_;
};

并从操作员处调用:

inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
   obj.stream_to(os);
   return os;
}

或者让操作员成为friend

class T {
  public:
    friend std::ostream& operator<<(std::ostream&, const T&);
  private:
    int data_;
};

这样它就可以访问类的私有部分:

inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
   os << obj.data_;
   return os;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“friend”函数和 << 运算符重载:为类重载运算符的正确方法是什么? 的相关文章

随机推荐