c++ - 在类和类的标题中重载 << 运算符时遇到问题

标签 c++ class io operator-overloading

所以我正在研究分数类程序,但我在重载输出运算符时遇到了一些困难。 主文件的相关位。

const fraction fr[] = {fraction(4, 8), fraction(-15,21),
                       fraction(10), fraction(12, -3),
                       fraction(), fraction(28, 6), fraction(0, 12)};

for (int i = 0; i < 7; i++){
    cout << "fraction [" << i <<"] = " << fr[i] << endl;
}

在fraction.h中

std::ostream& operator<<(std::ostream &out, const fraction &fr); //the location of the error. 

在类fraction.cpp文件中

ostream& operator<<(ostream& stream, const fraction& fr)
{
    if(fr.Denominator==1||fr.Numerator==0)
        stream << fr.Numerator;
    else
    stream << fr.Numerator << '/' << fr.Denominator << endl;
    return stream;
}

无论如何,错误代码很简单。 ‘std::ostream& fraction::operator<<(std::ostream&, const fraction&)’必须恰好接受一个参数|

我有点迷惑为什么它告诉我的是这个。 [它不能接受取 2 个值的函数吗?是 (std::ostream&, const fraction&) 完全错误吗?它应该只是括号中的单个参数吗?]

如果我的类(class)的 cpp 和头文件在作业中正确编码,则 main 函数是固定的并且可以工作。

我只在友元函数中做过 IO 重载,从来没有在友元函数中做过,即使是那些我也没有经验的函数,所以在这一点上我很迷茫。

最佳答案

编译器告诉您您正在尝试重载 operator <<对于两个参数,但在类运算符成员函数内部仅采用一个参数(即右侧参数)。如果它是 friend,您的代码将有效的 fraction因为您将定义一个带有两个参数的自由运算符函数。

所以要修复,要么在 fraction 之外定义函数或将其命名为 friend类的。当您将其命名为 friend , 该函数将能够访问类的任何实例的私有(private)成员。

关于c++ - 在类和类的标题中重载 << 运算符时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21370635/

相关文章:

C#从另一个文件访问父类方法

java - 从文件中读取时计算数字

python - 如何获取一个程序的输出并将其用作另一个程序的输入?

c++ - 如何在基类中使用接口(interface)?

python - 插入数据后更改类的类类型

c# - 在 Windows 中全局检测双击

ruby - Ruby 模块中的私有(private)类(不是类方法)?

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

c++ - 在 Visual Studio 中替换依赖项 DLL

android - 不支持的 OpenGL 函数和常量