0

我正在学习 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;
}
4

3 回答 3

2

operator >>()应该取TestClass&而不是const TestClass&作为它的第二个参数,因为您应该在读取时修改该参数istream

于 2016-07-28T15:30:32.647 回答
1

您应该将参数类型更改inObj为引用非常量,因为它应该在operator>>. 你不能修改 const 对象,所以你不能调用opeartor>>const 对象(及其成员),这就是编译器抱怨的。

friend istream& operator >> (istream& ins, TestClass& inObj);
于 2016-07-28T15:30:44.827 回答
1

删除限定符 const

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

您不能更改常量对象。

于 2016-07-28T15:31:08.180 回答