c++ - 'friend' 函数和 << 运算符重载 : What is the proper way to overload an operator for a class?

标签 c++ class operator-overloading friend friend-class

在我正在进行的一个项目中,我有一个 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 中的函数声明(实际上并未将其声明为成员)。

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

感谢您的宝贵时间!

编辑

我删除了对头文件重载的所有提及...但是我收到以下(也是唯一的)错误。 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

最佳答案

注意:您可能想查看 operator overloading FAQ .


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

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

请注意,它不是成员函数。另请注意,根据 const 流式传输对象引用。那是因为您不想复制对象以便对其进行流式传输,并且您也不希望流式传输更改它。


有时您希望流式传输其内部无法通过其类的公共(public)接口(interface)访问的对象,因此运算符(operator)无法获取它们。然后你有两个选择:要么将公共(public)成员放入进行流式传输的类中

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

并从运算符(operator)那里调用:

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_;
};

以便它可以访问类的私有(private)部分:

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

关于c++ - 'friend' 函数和 << 运算符重载 : What is the proper way to overload an operator for a class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2828280/

相关文章:

c++ - C++03 中的 result_of 类型特征

c++ - 当然有办法获得当前文件夹 View 的完整 View 下拉菜单吗?

c++ - fatal error LNK1120 : 4 unresolved externals

scala - 创建未命名的隐式类或函数

html - 如何使用 CSS 排除悬停效果

c++ - VS2012 支持 __asm__ __volatile__ 汇编代码

c++ - 在 C++ 中类应该以什么顺序声明?

c++ - 在 C++ 中的 operator= 之后调用的析构函数

Lua 5.3 使用 debug.setmetatable 覆盖整数值的 ~ (__bnot) 运算符

c# - 隐式转换运算符和相等运算符