2013-02-27 106 views
0

的代碼,我到目前爲止有:算術和賦值運算符重載 - 返回值,範圍,結合表達式

#include <iostream> 
#include <vector> 

using namespace std; 

class Dictionary 
{ 
private: 
    string dictName; 
    struct wordCard 
    { 
     string word; 
     string translation; 
    }; 
    vector<wordCard> Dict; 
    bool foundit = false; 
public: 
    // My attemtp at swap function for copy-and-swap: 
    void swap(Dictionary& dict1, Dictionary& dict2) 
    { 
     Dictionary dict3("tmp"); 
     dict3.dictName = dict1.dictName; 
     dict3.Dict = dict1.Dict; 
     dict1.dictName = dict2.dictName; 
     dict1.Dict = dict2.Dict; 
     dict2.dictName = dict3.dictName; 
     dict2.Dict = dict3.Dict; 
    } 
    // Very basic constructor (setting the dictionary name while creating an object was part of the assignment): 
    Dictionary(string name) 
    { 
     setDictName(name); 
    } 

    /* various functions that work fine */ 

    // Overloading "+" operator: 
    // The result is supposed to be a new dictionary (without changing the source) where all words from the 
    // original dictionaries are present without doubles. 
    Dictionary& operator+ (const Dictionary& dict) 
    { 
     bool doubleword = false; 
     string plusname; 
     plusname = "Augmenting " + this->dictName + " & " + dict.dictName; 
     Dictionary plusDict(plusname); 
     plusDict.Dict = this->Dict; 
     for (int i = 0; i < dict.Dict.size(); i++) 
     { 
      doubleword = false; 
      for (int i2 = 0; i2 < plusDict.Dict.size(); i2++) 
      { 
       if (plusDict.Dict[i2].word == dict.Dict[i].word) 
       { 
        doubleword = true; 
       } 
      } 
      if (!doubleword) 
      { 
       plusDict.Dict.push_back(dict.Dict[i]); 
      } 
     } 
     return *this; 
    } 

    /* 2 other overloads that are very similar */ 

    // Overloading "=" operator (using copy-and-swap): 
    // Not part of the assignment, but I couldn't think of another way to make the other operators work. 
    Dictionary& operator=(Dictionary dict) 
    { 
     swap(*this, dict); 
     return *this; 
    } 
}; 

及存在的問題,我與它:

理想的情況下,它應該像這樣工作:

Obj1 = result of operation Obj2 + Obj3; 

什麼我得到的時刻是:

Obj1 = Obj2 (ignores Obj3) 

我有一個模糊的想法,爲什麼發生(或實際上,兩個想法)。首先,operator+返回*this,而不是實際結果。但是,當我試圖將其更改爲臨時類對象時,編譯器開始對我尖叫。其次,我知道我使用的是局部變量(臨時類對象),但我不知道如何將其公開,以便稍後使用它。當我嘗試將類對象添加到public:部分(或private:)時,編譯器將其視爲函數聲明,而不是類對象。

所以,我無論怎樣才能讓我的臨時類對象公開,或返回a+b代替*this結果,或使operator=捕獲結果或operator+,而不是它返回什麼?

回答

2

operator +應該由值返回一個新對象,併爲const - 即像

Dictionary operator+ (const Dictionary& dict) const 
{ 
    Dictionary ret; 
    //modify ret 
    return ret; 
} 
+0

我試過了,但是編譯器說:'參考堆棧與局部變量「plusDict」 returned',然後記憶相關我仍然得到原始類對象而不是'plusDict'。 – Kaworu 2013-02-27 12:54:46

+0

@ user2115087是否通過任何機會通過引用返回? – 2013-02-27 13:01:33

+0

看起來像我做的。但是當我在'operator +'中將'Dictionary&'更改爲'Dictionary'時,它停止工作 - 它沒有顯示任何錯誤,但我甚至無法獲取字典名稱輸出。 – Kaworu 2013-02-27 13:19:10