简体   繁体   中英

error overloading operator '>>'

I am trying to overload the >> operator, check my code, it's the most reduced program:

#include <iostream>
#include <string>
using namespace std;

class MyClass{
private:
   string bar;
   int foo;

public:
   MyClass(){
   bar="";
   foo=0;
};

istream& operator>>(istream& is){
    is >> bar >> foo;
    return is;
};

ostream& operator<<(ostream& os){
    os << bar << foo;
    return os;
};

~MyClass(){};
};

int main()
{
    MyClass* a = new MyClass();

    cin >> *a;

    delete a;

    return 0;
}

This code doesn't compile , I've googled before post my question and I found the trouble could be the most vexing parse, but i cannot imagine how to fix it.

Anyway, I don't know where is the problem, when i try to compile, the compiler throws:

First:

error: no match for ‘operator>>’ (operand types are ‘std::istream {aka std::basic_istream<char>}’ and ‘MyClass’)
cin >> *a;
~~~~^~~~~

Then, after trying to convert the types to int, double, char, etc it throws:

/usr/include/c++/6.1.1/istream:924:5: nota: candidate: 
std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&&, _Tp&) [con _CharT = char; _Traits = std::char_traits<char>; _Tp = MyClass] <coincidencia cercana>
 operator>>(basic_istream<_CharT, _Traits>&& __is, _Tp& __x)
 ^~~~~~~~
/usr/include/c++/6.1.1/istream:924:5: nota:   conversion of argument 1 would be ill-formed:
error: no se puede unir el l-valor ‘std::istream {aka std::basic_istream<char>}’ a ‘std::basic_istream<char>&&’
cin >> *a;

What can I do to solve this issue?

Overloading the input and output operators can't be done as member functions. The reason is that when you defined the >> or << operators as member functions the object instance of the class must be on the left hand side of the operator.

Instead define the operator functions as non-member friend functions (which can be done inline in the class) like

class MyClass
{
public:
    ...

    friend std::ostream& operator<<(std::ostream& os, MyClass const& object)
    {
        return os << object.bar << object.foo;
    }
};

通常不会将“ >>”和“ <<”运算符实现为成员函数,因为第一个参数是该成员函数中该类的隐式对象,但是您可以这样做,并且如果您要进行* a>之类的操作,它将起作用。 >在您的主服务器中使用cin。否则,请按照上述答案中的说明将这些运算符实现为全局函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM