0

Ich lerne C++ stream operator overloading. Das kann nicht in Visual Studio kompiliert werden.C++ Kompilierfehler; stream operator overload

In der Operator-Sektion istream& hebt der Compiler die Karat kurz nach ins hervor und sagt no operator >> matches these operands.

Kann jemand es schnell ausführen und mir sagen, was los ist?

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

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

Vielen Dank SOOO viel !!! Ja Entfernen von "const" löste es, und es macht total Sinn !! – Timbo1711

Antwort

2

operator >>() sollte TestClass& statt const TestClass& als zweiten Parameter übernehmen, da Sie erwartet werden, dass die Parameter zu ändern, während sie von istream lesen.

1

Sie sollten den Parametertyp von inObj ändern, um auf nicht-const zu verweisen, da es in operator>> geändert werden soll. Sie können nicht an einem const-Objekt ändern, so dass Sie opeartor>> auf const-Objekt (und seine Mitglieder) nicht aufrufen können, das beschwert sich der Compiler.

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

den Qualifier const entfernen

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

Sie können keine konstante Objekt ändern.