【问题标题】:C++ compile error; stream operator overloadC++ 编译错误;流运算符重载
【发布时间】:2016-07-28 15:28:38
【问题描述】:

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

【问题讨论】:

  • 非常感谢你!!!是的,删除“const”解决了它,这完全有道理!

标签: c++ operator-overloading overloading operator-keyword stream-operators


【解决方案1】:

operator &gt;&gt;() 应该将TestClass&amp; 而不是const TestClass&amp; 作为它的第二个参数,因为您需要在从istream 读取时修改该参数。

【讨论】:

    【解决方案2】:

    您应该将inObj 的参数类型更改为引用非常量,因为它应该在operator&gt;&gt; 中进行修改。您不能修改 const 对象,因此不能在 const 对象(及其成员)上调用 opeartor&gt;&gt;,这就是编译器抱怨的原因。

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

    【讨论】:

      【解决方案3】:

      删除限定符 const

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

      您不能更改常量对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-13
        相关资源
        最近更新 更多