其他分享
首页 > 其他分享> > c-<<运算符重写为cout int和double值

c-<<运算符重写为cout int和double值

作者:互联网

我需要重写<<运算符,以便它可以表示小时(int)和温度(double)的值. 我想我已经包括了所有必要的部分.提前致谢.

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)
{
    // unsure what to enter here

    return ost;
}

========

vector<Reading> get_temps()
{
// stub version                                                                 
    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));
    }

}

解决方法:

例如这样:

bool operator <(Reading const& left, Reading const& right)
{
    return left.temperature < right.temperature;
}

并且它应该是一个全局函数(或与Reading相同的名称空间),而不是成员或Reading,如果您要拥有任何受保护的成员或私有成员,则应将其声明为朋友.可以这样完成:

struct Reading {
    int hour;
    double temperature;
    Reading(int h, double t): hour(h), temperature(t) { }

    friend bool operator <(Reading const& left, Reading const& right);
};

标签:ostream,c,iostream
来源: https://codeday.me/bug/20191013/1906542.html