2013-02-27 72 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