【问题标题】:Can you switch the sides of operator+可以切换operator+的边吗
【发布时间】: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 不需要定义,除非您还定义了函数。

标签: c++ operator-overloading


【解决方案1】:

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

【讨论】:

  • 整个 operator+ 方法会很慢,复制字符串的链表数百万次。放手吧。
  • 我应该注意我的类都是由头文件和实现文件分隔的。所以我尝试了两种方法。第一种方法一直给我一个错误,说该函数已在其他地方定义。另一个给我一个错误,说类 Sentence 是如何不完整的。几个小时以来,我一直在尝试解决那里的错误。
  • @user3400223:这还不足以理解发生了什么。我建议用代码 sn-ps 和错误消息问另一个问题。
猜你喜欢
  • 2010-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-15
  • 2013-05-23
  • 2021-10-25
  • 2010-10-01
  • 1970-01-01
相关资源
最近更新 更多