Timbo1711
Timbo1711

Reputation: 7

C++ compile error; stream operator overload

I'm learning C++ stream operator overloading. Can't get this to compile in Visual Studio.

In the istream& operator section, the compiler highlights the carats just after ins and says no operator >> matches these operands.

Can someone quick run it and tell me what's wrong?

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

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

Upvotes: 0

Views: 90

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

Remove the qualifier const

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

You may not change a constant object.

Upvotes: 1

songyuanyao
songyuanyao

Reputation: 172864

You should change the parameter type of inObj to reference to non-const, since it's supposed to be modified in operator>>. You can't modify on a const object, so you can't call opeartor>> on const object (and its members), that's what compiler complains.

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

Upvotes: 1

timrau
timrau

Reputation: 23058

operator >>() should take TestClass& instead of const TestClass& as its 2nd parameter since you are expected to modify that parameter while reading from istream.

Upvotes: 2

Related Questions