【问题标题】:Overloading an operator C++: error: no viable overloaded '='重载运算符 C++:错误:没有可行的重载 '='
【发布时间】:2015-10-08 18:19:06
【问题描述】:

我的目标是重载“+”运算符,这样我就可以组合段落对象和故事对象。此函数应该返回一个新的 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;
}

但是,当我运行所有代码时(Story 对象应该有一个段落。Paragraph 对象应该有一个句子。Sentence 对象应该有一个单词,等等),我得到了这个错误:

错误:没有可行的重载'='

当我尝试执行以下操作时会发生这种情况:

paragraph.sentence = this->sentence + paraSentence;

我不太确定如何将句子组合在一起形成一个段落(最终形成并返回一个新故事)。有谁知道如何解决这个问题?

【问题讨论】:

  • “你可以假设我所有的类都被正确定义了” 如果这是真的,你就不会出错...
  • Sentence 类是否有复制构造函数或重载的= 运算符?
  • 什么问题?我们看不到任何相关的代码。出示您过去几天用来调试问题的minimal testcase
  • 告诉我们Sentence的定义。
  • Word 是...?另外,段落不是一个或多个句子吗?那么为什么Paragraph 中只有一个 Sentence 对象?

标签: c++ operator-overloading overloading addition


【解决方案1】:
you can assume that all my classes are defined properly

这是导致您出现此错误的错误假设。 Sentence 类显然没有或错误的 operator= 和/或 复制构造函数 已定义

【讨论】:

  • s/拷贝构造函数/拷贝赋值运算符
  • 肯定是编译器错误,因为代码是正确的:-)
  • 哦,我忘了实现正确的 operator= 。谢谢。我会按照以下方式做一些事情吗? Story 对象 + Paragraph 对象等于新的 Story 对象? (以及所有其他重载的 operator='s)。
  • @raychul 向我们展示Paragraph 类。
【解决方案2】:
Paragraph operator+(const Sentence& sent);

这声明了一个运算符,这样添加两个Sentences 就会产生一个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;              

};

当两个Sentences相加返回一个Sentence,那么相加的结果也可以赋值给一个Sentence,因为编译器会自动生成相同类型的复制赋值(除非你明确@ 987654339@它)。

但这也带来了一些问题,因为两个句子如何在逻辑上合二为一?

真正的问题大概可以在这一行找到:

Sentence sentence;      // Sentence in Paragraph

你的类定义有效地表明一个段落总是由一个句子组成。这不可能是正确的。成员变量应为std::vector&lt;Sentence&gt; 类型,以表达一个段落由0 到n 个句子组成的意图。更改成员变量后,重写所有运算符实现以适应新情况。

当然,你在Sentence 也有同样的问题(我猜你的其他课程也有)。


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

【讨论】:

    猜你喜欢
    • 2015-06-24
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 2017-05-03
    相关资源
    最近更新 更多