2010-12-05 64 views
1

我需要重写< <运算符,以便它可以输出小时(int)和温度(双精度)的值。<<运算符重写为cout 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)); 
    } 

}

+5

这是功课? – 2010-12-05 23:57:05

+2

你的问题是什么?你是要求我们为你写你的功能吗? – Gabe 2010-12-06 00:01:33

回答

2

使用OST参数比如std ::法院在运营商< <。

3

你可能要像

ost << r.hour << ' ' << r.temperature; 

这是很简单的东西,不过,如果它是没有意义的,你真的应该跟某人或得到一本书。

如果它仍然没有道理或你不能被打扰,考虑选择另一个爱好/职业。

2
r.hour() 
r.temperature() 

您已经声明hourtemperature为成员领域Reading,不是会员方法。因此它们只是r.hourr.temperature(不是())。

1

由于小时和温度是变量而不是函数,只需从operator<<函数中删除尾随的()即可。

4

例如像这样:

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

它应该是一个全局函数(或在同一个命名空间Reading),而不是一个成员或Reading,它应该如果你要被声明为friend有任何保护或私人成员。这可以这样做:

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

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

你可以在C++中重载这样的操作符。

struct Reading { 
    int hour; 
    double temperature; 
    Reading(int h, double t): hour(h), temperature(t) { } 
    bool operator<(struct Reading &other) { 
     //do your comparisons between this and other and return a value 
    } 
} 
3

IIRC,你可以做以下两种方式之一...

// overload operator< 
bool operator< (const Reading & lhs, const Reading & rhs) 
{ 
    return lhs.temperature < rhs.temperature; 
} 

或者,您可以将操作添加到您的结构......

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