0

可能重复:
C++:<<运算符重写为 cout int 和 double 值

我需要重写 << 运算符,以便它可以计算小时(int)和温度(double)的值。

我想我已经包含了所有必要的部分。有问题的部分是 ostream& 运算符<<

它给了我错误:

proj4.cc:87: error: ‘r->Reading::hour’ cannot be used as a function
proj4.cc:88: error: ‘r->Reading::temperature’ cannot be used as a function

我可以简单地将它们重写为 r.hour 和 r.temperature 吗?

谢谢。

==================

struct Reading {
    int hour;
    double temperature;
    Reading(int h, double t): hour(h), temperature(t) { }
    bool operator<(const Reading &r) const;
};

========

ostream& operator<<(ostream& ost, const Reading &r)
{
    return ost << '(' << r.hour()
               << ',' << r.temperature() <<')';

}

========

vector<Reading> get_temps()
{                                                             
    cout << "Please enter name of input file name: ";
    string name;
    cin >> name;
    ifstream ist(name.c_str());
    if(!ist) error("can't open input file ", name);

    vector<Reading> temps;
    int hour;
    double temperature;
    while (ist >> hour >> temperature){
        if (hour <0 || 23 <hour) error("hour out of range");
        temps.push_back( Reading(hour,temperature));
    }

}

4

0 回答 0