0

我正在學習C++流操作符重載。無法在Visual Studio中進行編譯。C++編譯錯誤;流操作符過載

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

謝謝SOOO很多!是的刪除「const」解決了它,它完全有道理! – Timbo1711

回答

2

operator >>()應採取TestClass&而不是const TestClass&作爲其第二個參數,因爲你預期,同時從istream讀來修改參數。

1

您應該更改參數類型inObj以引用非常量,因爲它應該在operator>>中修改。你不能在const對象上修改,所以你不能在const對象(及其成員)上調用opeartor>>,這就是編譯器的抱怨。

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

取下標識const

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

你不能改變一個常量對象。