2013-02-24 76 views
1

我試圖重載流運算符<<但它仍然只是打印對象的地址,而不是對象的信息,如我在過載功能的定義。這是我的代碼,花了很長時間嘗試在網上找到的每個例子,但沒有任何工作。請幫助緩解我的一些壓力!謝謝。重載<<運算符不起作用;還是打印對象地址

Interval.h:

#ifndef INTERVAL_H 
#define INTERVAL_H 
#include <string> 
#include <iostream> 
#include <assert.h> 

using namespace std; 

class Interval { 
    public: 
     long start; 
     long end; 

     // Constructor 
     Interval(long, long); 

     // Deconstructor 
     // Virtual to make sure that it calls the correct destructor 
     virtual ~Interval(); 

     bool operator==(const Interval &other) const; 
     bool operator!=(const Interval &other) const; 
     bool operator<(const Interval &other) const; 
     bool operator<=(const Interval &other) const; 
     bool operator>(const Interval &other) const; 
     bool operator>=(const Interval &other) const; 
     friend ostream& operator<<(ostream& os, const Interval &i); 

}; 
#endif 

Interval.cpp:

#include "Interval.h" 
#include <iostream> 
#include <string> 

using namespace std; 

Interval::Interval(long a, long b){ 
    // Assert that start is less than the end 
    assert(a < b); 
    start = a; 
    end = b; 
} 

// Deconstructor 
Interval::~Interval(){ 
} 

bool Interval::operator==(const Interval &other) const{ 
    // Return true if both start and end are equal to other's 
    if(start == other.start && end == other.end){ 
     return true; 
    }else{ 
     return false; 
    } 
} 

bool Interval::operator!=(const Interval &other) const{ 
    // Return true(not equal) if either the start or end are different 
    if(start != other.start || end != other.end){ 
     return true; 
    }else{ 
     return false; 
    } 
} 
bool Interval::operator<=(const Interval &other) const{ 
    // Return true if the start is less than or equal other's start 
    if(start <= other.start){ 
     return true; 
    } 
} 

bool Interval::operator>(const Interval &other) const{ 
    // Return true if the end is greater than other's end 
    if(end > other.end){ 
     return true; 
    } 
} 

bool Interval::operator>=(const Interval &other) const{ 
    // Return true if the end is greater than or equal to other's end 
    if(end >= other.end){ 
     return true; 
    } 
} 


bool Interval::operator<(const Interval &other) const{ 
    // Return true if the start is less than other's 
    if(start < other.start){ 
     return true; 
    } 
} 

ostream& operator<<(ostream& os, const Interval &i){ 

    os << "Interval[" << i.start << ", " << i.end << "]" << endl; 
    return os; 
} 

int main(void){ 
    Interval *test = new Interval(10,1000); 
    cout << test << endl; 
    cout << "test" << endl; 
} 

回答

5

Interval*是一個指針。你只是輸出地址。

嘗試取消引用指針:

cout << *test << endl; 

或者試試這個:

Interval test(10, 1000); // not a pointer. 
cout << test << endl; 
+0

我認真無法相信我忽視了。非常感謝! – midma101 2013-02-24 22:49:49

1
Interval *test = new Interval(10,1000); 

在C++在棧上創建對象的語法是

Interval test(10,1000); 

唐除非你有良好的心態,否則不要使用指針就這樣做。