<<运算符重写为cout int和double值 [英] << Operator Rewrite to cout int and double values

查看:55
本文介绍了<<运算符重写为cout int和double值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to rewrite the << operator so that it can cout values for hour (int) and temperature (double).

我想我已经包括了所有必要的部分.预先感谢.

I think I've included all necessary sections. Thanks in advance.

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,如果您要具有任何受保护的成员或私有成员,则应将其声明为friend.可以这样完成:

And it should be a global function (or in the same namespace as Reading), not a member or Reading, it should be declared as a friend if you going to have any protected or private members. This could be done like so:

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

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

这篇关于&lt;&lt;运算符重写为cout int和double值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆