2011-01-08 83 views
2
#include<iostream> 
using namespace std; 

class aClass 
{ 
public: 
    char *message; 

    aClass(const char *message); 
    ~aClass(){delete[] message;} 
}; 

aClass::aClass(const char* newmessage) 
{ 
    message = new char[strlen(newmessage) +1]; 
    strcpy(message,newmessage); 
} 

const ostream& operator<<(const ostream& o, const aClass &a) 
{ 
    o << a.message; 
    return o; 
} 

int main() 
{ 
    aClass b("Hello"); 
    cout << b; 
} 

有人可以向我解釋爲什麼上面的代碼產生無限循環嗎?超載時出現堆棧溢出<<運算符

+1

爲什麼不直接使用'的std :: string`? – 2011-01-08 22:11:17

+0

請注意,您違反了[三條規則](http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29)。如果我複製你的課堂,繁榮。你還需要一個拷貝構造函數和賦值操作符,使用[copy-and-swap idiom](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom)。請注意,您應該只是使用`std :: vector `或`std :: string`。 – GManNickG 2011-01-08 22:11:45

回答

11

因爲你有const它不應該是:

/////      ///// 
const ostream& operator<<(const ostream& o, const aClass &a) 

輸出流被假設是非常量;畢竟,輸出數據正在改變一些東西。所以,當你這樣做:

o << a.message; 

它不能正常使用的過載char*,因爲一個在非const流進行操作。相反,它會搜索適當的過載並找到你的,並確定它可以從a.message(因爲你的構造函數不是explicit)構造一個aClass,並且調用它。這永遠重複。

應該寫成:

ostream& operator<<(ostream& o, const aClass &a) 
{ 
    o << a.message; 
    return o; 
}