运算符类型ifstream和double不匹配operator >>

Mor*_*ten -2 c++

我有运算符重载的问题.我有一个名为的类Point1,定义为

class Point1 {
private:
    long double x;
public:
    Point1(): x(0) {}
    Point1(long double val): x(val) {}
    Point1(Point1 & val): x(val.x) {}
    //Some functions omitted
    friend ofstream& operator<< (ofstream&, const Point1&);
    friend ifstream& operator>> (ifstream&, Point1&);
};
Run Code Online (Sandbox Code Playgroud)

这个类正在工作,为其执行operator>>(ifstream&, Point1&);,其功能主体是:

double tmp;
in >> tmp; //In this line g++ breaks with an error
pnt.x=tmp;
return in;
Run Code Online (Sandbox Code Playgroud)

我在debian测试中使用gcc 4.9.3(armv7l).完整的源代码可以在这里找到:http://hastebin.com/igunaquxiw.cpp

Rob*_*ski 7

您为文件重载了流操作符,但您没有使用文件I/O而是控制台输入.

cin >> pnt >> pnt2;
Run Code Online (Sandbox Code Playgroud)

改成

friend ostream& operator<< (ostream& s, const Point1& p)
{
    s << p.x;
    return s;
}
friend istream& operator>> (istream& s, Point1& p)
{
    s >> p.x;
    return s;
}
Run Code Online (Sandbox Code Playgroud)

如果你比较这里的类型,那么cin操作的类型就会被重载,有些信息 http://en.cppreference.com/w/cpp/io/cin http://en.cppreference.com/w/cpp/io/basic_ifstream http://en.cppreference.com/w/cpp/io/basic_istream

Cin的类型为istream,但此类型没有运算符,ifstream只有运算符.