重载运算符 C++:错误:没有可行的重载'='
Overloading an operator C++: error: no viable overloaded '='
我的目标是重载'+'操作符,这样我就可以组合一个段落对象和一个故事对象。这个函数应该返回一个新的Story对象,并将段落附加到开头。
Story Paragraph::operator+(const Story& story) {
Paragraph paragraph;
Story stry;
Paragraph storyPara = story.paragraph;
Sentence paraSentence = storyPara.sentence;
paragraph.sentence = this->sentence + paraSentence;
stry.paragraph = paragraph;
return stry;
}
然而,当我运行所有的代码(一个故事对象应该有一个段落。段落对象应该有一个句子。一个句子对象应该有一个单词,等等),我得到这个错误:
错误:没有可行的重载"="
当我尝试执行以下行时,会出现这种情况:
paragraph.sentence = this->sentence + paraSentence;
我不太确定如何将这些句子加在一起形成一个段落(最终形成&返回一个新的Story)。有人知道怎么解决这个问题吗?
you can assume that all my classes are defined properly
是错误的假设导致了这个错误。Sentence
类显然没有或错误地定义operator=
和/或复制构造函数
Paragraph operator+(const Sentence& sent);
声明了一个运算符,使得两个Sentence
相加得到一个Paragraph
。
paragraph.sentence = this->sentence + paraSentence;
赋值的右边部分使用了上面的操作符,所以你试图将Paragraph
传递给Sentence
,就好像你写了:
Paragraph additionResult = this->sentence + paraSentence;
paragraph.sentence = additionResult;
问题是您没有在Sentence
中定义Paragraph
的赋值。当然,您可以直接将其添加到Sentence
:
Sentence& operator=(const Paragraph& para);
但是你如何实现呢?一个段落能在逻辑上转换成一个句子吗?
另一种解决方案是将Sentence
中相应的operator+
更改为返回Sentence
而不是段落:
class Sentence {
public:
Sentence();
~Sentence();
void show();
Sentence operator+(const Sentence& sent); // <-- now returns a Sentence
Paragraph operator+(const Paragraph& paragraph);
Sentence operator+(const Word& word);
Word word;
};
当两个Sentence
相加返回一个Sentence
时,则相加的结果也可以赋值给一个Sentence
,因为编译器会自动生成相同类型的拷贝赋值(除非您显式地将其赋值为delete
)。
但是这也有它自己的问题,因为两个句子怎么能在逻辑上组合成一个句子呢?
真正的问题可以在这一行找到:
Sentence sentence; // Sentence in Paragraph
你的类定义有效地说明了一个段落总是恰好由一个句子组成。这是不正确的。成员变量应该是std::vector<Sentence>
类型,以表达一个段落由0到n个句子组成的意图。一旦你改变了成员变量,重写所有的操作符实现以适应新的情况。
当然,你在Sentence
中也有同样的问题(我猜在你的其他类中也是如此)。
一般来说,请再次查看您的书籍/教程,并复习有关操作符重载的章节。您没有遵循最佳实践。例如,您应该根据+=
来定义+
。当然,一个重要的问题是操作符重载在这里是否真的有用。
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用