你能把话务员+的两边换一下吗

Can you switch the sides of operator+

本文关键字:一下 话务员      更新时间:2023-10-16

所以基本上我有一个类"Sentence",#包括"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

有没有一种方法可以翻转运算符+重载的右手边和左手边,这样我就可以把代码放在句子类中。

我不能把代码放在句子类中,因为我需要的地方有一个单独的重载函数

s+w 

返回一个单词添加到末尾的句子

在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 {
    ...
}