2010-12-05 48 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; } 
}