2010-12-05 8 views
1

< < 연산자를 다시 작성해야 시간 (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)); 
    } 

} 표준 : : cout과 같은

+5

이 숙제인가 할 수 있습니까? –

+2

무엇이 당신의 질문입니까? 우리에게 당신을 위해 당신의 기능을 쓰라고 하시겠습니까? – Gabe

+0

중복 : http://stackoverflow.com/questions/4362077/c-operator-rewrite-to-cout-int-and-double-values ​​동일/유사한 질문 2 개를 요청할 필요가 없습니다. –

답변

2

사용 OST 매개 변수 in 연산자 < <.

3

당신은 아마이 비록 아주 간단 물건을하고, 그것을 이해가되지 않는 경우에 당신이 정말로 누군가에게 이야기하거나 책을 얻어야한다

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

같은 것을 원한다.

아직 이해가되지 않거나 괴롭히지 않는 경우 다른 취미/직업을 선택하는 것이 좋습니다.

2
r.hour() 
r.temperature() 

당신은 회원으로Reading필드가 아닌 멤버 방법hourtemperature을 선언했습니다. 따라서 그들은 단순히 r.hourr.temperature (no ())입니다.

1

시간과 온도가 기능이 아니라 변수이기 때문에 함수에서 후행 ()을 제거하면됩니다.

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); 
}; 
+0

연산자 정의가 구조체와 동일한 네임 스페이스에 있는지 확인하십시오. 그러면 인수 종속적 인 조회 중에 연산자 정의를 찾을 수 있습니다. –

+0

'struct'의 private 멤버를 가질 수 있다고 생각하지 못했습니다 - 클래스가 아니겠습니까? 이 경우 네, 개인/보호 된 멤버가 액세스 할 수 있도록'친구 '를 사용하십시오. – Will

+0

호기심에서 벗어난 이유는 회원 기능이 아니어야한다고 말하는 이유를 확장 할 수 있습니까? – Will

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; } 
}