【发布时间】:2014-10-17 08:30:47
【问题描述】:
所以基本上我有一个“句子”类#includes“Word”。
句子是单词的链表
这是我的问题
"Word + Sentence 返回一个新的句子,其中单词添加到开头" 所以基本上
Word w = "The";
Sentence s = "dog jumped high."
//the object type of w+s should be a sentence
但是,我得到了错误,
'Sentence' does not name a type
//this is in reference to the return type of overloaded operator+ function, which is in the word class
那么有没有办法翻转 operator+ 重载的左右两侧,以便我可以将代码放入 Sentence 类中。
我无法将代码放在 Sentence 类中,因为我需要一个单独的重载函数
s+w
返回一个在末尾添加单词的句子
【问题讨论】:
-
问题是在定义
Sentence类之前,您不能声明返回Sentence的函数。为避免此问题,请使用非成员运算符重载(无论如何这是个好主意)。 See here for a full rundown -
给句子一个非显式构造函数,它需要一个单词来创建一个 1 单词的句子。现在你只需要一个非成员 operator+ 带两个句子,你也可以给它传词。
-
@MattMcNabb:这是不正确的。只要声明了
Sentence,就可以声明返回Sentence的函数。Sentence不需要定义,除非您还定义了函数。