重载运算符 C++:错误:没有可行的重载'='

Overloading an operator C++: error: no viable overloaded '='

本文关键字:重载 运算符 C++ 错误      更新时间:2023-10-16

我的目标是重载'+'操作符,这样我就可以组合一个段落对象和一个故事对象。这个函数应该返回一个新的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中也有同样的问题(我猜在你的其他类中也是如此)。


一般来说,请再次查看您的书籍/教程,并复习有关操作符重载的章节。您没有遵循最佳实践。例如,您应该根据+=来定义+。当然,一个重要的问题是操作符重载在这里是否真的有用。