[英]C++ compile error; stream operator overload
我正在學習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
讀取數據時,您應該修改該參數。
您應該將inObj
的參數類型inObj
為引用非常量,因為應該在operator>>
對其進行修改。 您不能在const對象上進行修改,因此不能在const對象(及其成員)上調用opeartor>>
,這就是編譯器抱怨的地方。
friend istream& operator >> (istream& ins, TestClass& inObj);
刪除限定符const
friend istream& operator >> (istream& ins, const TestClass& inObj);
^^^^^
您不能更改常量對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.