2017-10-28 70 views
0

,因爲我不允許使用的std :: string對我使用所謂的charstring類型爲那些情況下,我不能初始化它自己的包裝定製類的任務。操作>>對於一個char指針包裝

類看起來是這樣的:

struct CharString { 
    char* str; 
    CharString() : str() {} // Initialize NULL 
    ~CharString() { free(str); } 
    // Conversions to be usable with C functions 
    operator char**() { return &str; } 
    operator char*() { return str; } 
}; 

然而,當我想用​​就可以了>>我碰到下面的錯誤。

binary '>>': no operator found which takes a right-hand operand of type 'utils::CharString' (or there is no acceptable conversion). 

我如何使用操作符重載>>

CharString operator>>(std::istream& is) { 
    is >> str; 
    return *this; 
}; 

我嘗試了上面的但仍然給我同樣的錯誤。

回答

1

重載流提取運算符的一般方法是提供一個友元函數與一般形式:

istream& operator>> (istream& in, MyObjectType& object) { 
    // read all the data you need to construct an object. 
    // 
    // Then: 
    if (in) { // Read succeeded! Update object. 
     // Build a new object of the appropriate type. 
     MyObjectType theOneIRead(basedOnTheDataIRead); 

     // Swap the object you were given as input for the one you 
     // just read. This way, if the read completely succeeds, you 
     // update the rhs, and if the read failed, nothing happens. 
     std::swap(object, theOneIRead); 
    } 
    return in; 
} 

注意這個函數的簽名會比你寫的不同。

你需要採取與讀一個字符從流的時間和構建某種臨時緩衝區來保存它們相關的邏輯的照顧。這是不平凡的,是它爲什麼這麼高興,我們有一個std::string型與庫打包的原因之一。但除此之外,遵循下面的模板應該給你你想要的。

獨立 - 你的結構目前有一個析構函數,但沒有拷貝構造函數,移動構造函數或賦值操作符。通常情況下,你會想,也能實現旁邊的析構函數這些功能,否則複製你的對象最終會做指針的淺拷貝,並導致記憶問題,兩個獨立的對象嘗試釋放相同的指針。

此外,由於這是C++,因此請考慮使用new[]delete[]而不是mallocfree

+0

我想我需要把這個在我的charstring類型結構,但這種藏漢給我的錯誤:'當我使用這兩個參數不能只超載或'這個操作符function'太多的參數使用IStream的時候返回類型alone'區分功能。 – IMarks

+1

這應該是一個朋友功能,而不是一個成員函數。確保在課堂外聲明它,然後在課堂內爲它添加一個朋友聲明。 – templatetypedef