你可以切换操作员+的侧面

时间:2014-10-17 00:27:45

标签: c++ operator-overloading

所以基本上我有一个“句子”,#include“Word”。

句子是单词的链接

这是我的问题

“Word + Sentence返回一个新的句子,Word添加到开头” 所以基本上

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

那么有没有办法翻转操作符的右侧和左侧+重载,以便我可以将代码放在Sentence类中。

我无法将代码放在Sentence类中,因为我需要一个单独的重载函数

s+w 

返回一个带有添加到结尾的单词的句子

1 个答案:

答案 0 :(得分:4)

在C ++中,运营商根本不必是成员。所以只需在类之外定义运算符:

Sentence operator+(const Word &word, const Sentence &sentence);

另请注意,您可以转发声明类:

class Sentence; // forward declaration

class Word {
    Sentence operator+(const Sentence &sentence) const;
};

class Sentence {
    ...
};

// Now that Sentence is defined (not just declared),
// you can define operator+ for Word (instead of just declaring it)
Sentence Word::operator+(const Sentence &sentence) const {
    ...
}