重载" >> " 程序崩溃

Overloading " >> " Crashed the program

本文关键字:gt 崩溃 程序 重载      更新时间:2023-10-16
#include <iostream>
#include <sstream>
using namespace std;
class Rupee{
    private:
        int number;
        int number2;
        int number3;
    public:
    Rupee()
    {
    }
    friend ostream &operator<<( ostream &os, const Rupee &e );
    friend istream &operator>>( istream &is, const Rupee &e );
};

    ostream& operator << (ostream & os ,const Rupee &e)
    {
        os<<endl << e.number << endl;
        os << e.number2<< endl;
        os << e.number3<< endl;
        return os;
    }
    istream& operator >> (istream & is ,const Rupee &e)
    {
        is>>e.number>>e.number2>>e.number3;
        return is;
    }

int main()
{
    Rupee o1;
    cin >> o1;
    cout << o1;
}

你好,我正在尝试使操作员<<重载。当IM运行程序时,程序不为" << "运行,但适用于" >> "。我在哪里做错?我是否使用正确的iStream和Ostream类来用于超载功能?

评论者提到的编译问题是将const引用传递给>>运算符。值被读取到变量中,因此使其构成导致编译器错误,应删除const关键字:

friend istream &operator >> (istream &is, Rupee &e);
istream& operator >> (istream & is, Rupee &e)

进行了这些更改后,程序编译并为我运行良好,Visual Studio 2015在这里。但是,您可能需要暂停出口上的程序以读取输出:

cin.ignore();
cin.get();