C++编译错误;流运算符重载

标签 c++ operator-overloading overloading operator-keyword stream-operators

我正在学习 C++ 流运算符重载。无法在 Visual Studio 中进行编译。

istream&运算符部分,编译器会突出显示 ins 之后的克拉并说no operator >> matches these operands .

有人可以快速运行它并告诉我哪里出了问题吗?

*****************

// CoutCinOverload.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;

class TestClass {

friend istream& operator >> (istream& ins, const TestClass& inObj);

friend ostream& operator << (ostream& outs, const TestClass& inObj);

public:
    TestClass();
    TestClass(int v1, int v2);
    void showData();
    void output(ostream& outs);
private:
    int variable1;
    int variable2;
};

int main()
{
    TestClass obj1(1, 3), obj2 ;
    cout << "Enter the two variables for obj2: " << endl;
    cin >> obj2;  // uses >> overload
    cout << "obj1 values:" << endl;
    obj1.showData();
    obj1.output(cout);
    cout << "obj1 from overloaded carats: " << obj1 << endl;
    cout << "obj2 values:" << endl;
    obj2.showData();
    obj2.output(cout);
    cout << "obj2 from overloaded carats: " << obj2 << endl;

    char hold;
    cin >> hold;
    return 0;
}

TestClass::TestClass() : variable1(0), variable2(0)
{
}

TestClass::TestClass(int v1, int v2)
{
    variable1 = v1;
    variable2 = v2;
}

void TestClass::showData()
{
    cout << "variable1 is " << variable1 << endl;
    cout << "variable2 is " << variable2 << endl;
}

istream& operator >> (istream& ins, const TestClass& inObj)
{
    ins >> inObj.variable1 >> inObj.variable2;
    return ins;
}

ostream& operator << (ostream& outs, const TestClass& inObj)
{
    outs << "var1=" << inObj.variable1 << " var2=" << inObj.variable2 << endl;
    return outs;
}

void TestClass::output(ostream& outs)
{
    outs << "var1 and var2 are " << variable1 << " " << variable2 << endl;
}

最佳答案

operator >>() 应该将 TestClass& 而不是 const TestClass& 作为它的第二个参数,因为你应该在阅读时修改那个参数来自 istream

关于C++编译错误;流运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38640709/

相关文章:

c++ - 为什么 std::vector::at() 即使启用了优化也需要边界检查?

c++ - 如何正确转换也是不同数据类型的各种(已知)长度数据包的流?

c# - 从 C# 调用 C++ dll 中的方法,没有任何信息,只有头文件

PowerShell 中的函数重载

types - 在 F# 中,具有不同 arity 和返回类型的两个函数可以共享一个名称吗?

c++ - 接受字符串来调用函数

.net - 在 F# 中重载 "="和 "<>"

c++ - 为类中嵌套的枚举定义运算符

c# - 字符串转换不起作用

Java:重载相互调用的构造函数