gpt4 book ai didi

c++ - 算术和赋值运算符重载 - 返回值、范围、组合表达式

转载 作者:行者123 更新时间:2023-11-28 03:22:10 24 4
gpt4 key购买 nike

我目前的代码:

#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+ 而不是它返回的内容?

最佳答案

operator + 应该按值返回一个新对象并且是 const - 即类似于

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

关于c++ - 算术和赋值运算符重载 - 返回值、范围、组合表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15112350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com