2015-10-08 101 views
-2

我的目标是重载'+'运算符,以便我可以组合Paragraph对象和Story对象。此功能应该返回一个新的故事对象与附加到开头的段落。重载运算符C++:错误:没有可行的重载'='

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; 
} 

然而,当我跑我的所有代码(A故事的对象应该有一个段落。段落对象应该有一个句子,一个句子对象应该有一个字,等),我得到这个错误:

错误:没有合适的重载 '='

当我尝试做下面的行会发生此:

paragraph.sentence = this->sentence + paraSentence; 

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

+8

_“你可以假设我所有的类都被正确定义了”_如果这是真的,你就不会有错误... –

+0

'Sentence'类是否有复制构造函数或重载的'='运算符? – yizzlez

+0

什么问题?我们看不到任何相关的代码。出示您在过去几天内一直在调试该问题的[最小测试用例](http://stackoverflow.com/help/mcve)。 –

回答

3
you can assume that all my classes are defined properly 

这是错误的假设,导致你这个错误。 Sentence类显然已经没什么错operator=和/或拷贝构造函数定义

+0

或者错误的'operator ='。 –

+0

s /拷贝构造函数/拷贝赋值运算符 – Barry

+1

绑定是一个编译器错误,假设代码是正确的:-) – pm100

0
Paragraph operator+(const Sentence& sent); 

此声明的操作,从而增加了两个Sentence S IN一个Paragraph结果。

paragraph.sentence = this->sentence + paraSentence; 

分配的右边部分使用从上面的操作,让您尝试assing一个ParagraphSentence,因为如果你这样写:

Paragraph additionResult = this->sentence + paraSentence; 
paragraph.sentence = additionResult; 

的问题是,你有没有在Sentence中定义Paragraph的转让。你可以只将它添加到Sentence,当然:

Sentence& operator=(const Paragraph& para); 

但你怎么会实施呢?逻辑上可以将一个段落转换为单个句子吗?这个解决方案不会真的起作用。

另一种解决方案是改变对应于Sentenceoperator+返回一个,而不是一个段落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也有同样的问题(我猜你也在其他课上)。


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