【问题标题】:return type of class function not defined类函数的返回类型未定义
【发布时间】:2014-10-19 18:06:59
【问题描述】:

所以我有一个“句子”类#includes“单词”。

句子是单词的链表。

我的作业表明我必须重载“operator+”以便

Sentence s = "dog jumped.";
Word w = "The";

W+s; //should return a new sentence that says "The dog jumped high."

请记住,我必须重载 operator+。这就是我的评分标准

但是,由于 Sentence 包含 Word,因此尚未定义。会报错

return type 'class Sentence' is incomplete

和 不完整类型'const class Sentence'的无效使用

这是我的重载代码

class Sentence; //forward declaration
Sentence Word::operator+(const Sentence &sentence) const{
  Sentence *s = new Sentence(sentence.getCopy()); //make a new sentence that's a copy of the     parameter
  Word *w = new Word;

  Sentence::node *l = new Sentence::node; //make new linked list node
  (*(l->w)) = (*w); //Set word of node
  l->next = (*s).getFirs(); // set new node to point to first node of the sentence object
  (*s).setFirs(l); // point first pointer to the new node

  return *s;
}

我还尝试了一种在看起来像这样的类之外重载运算符的单独方法

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

这导致错误说它被定义了多次

【问题讨论】:

  • 您尝试返回仅前向声明的类型。假设你是编译器,用户说将来某个地方会有类 Sentance,所以你只知道一件事,然后他试图返回它的实例。您无法真正知道大小是多少,因此要为临时分配多少空间等。您必须拆分此代码,以便 operator+ 位于可以看到 Sentence 和 Word 定义的位置
  • 在类之外定义这个操作符是在这种情况下要走的路,可能通过友元声明或实用函数来辅助。为什么它不起作用?不知道,你肯定是搞错了,但是不看代码也说不准(当然是简化为最小的例子)。
  • 您似乎已经发布相同的代码好几天了,但仍然没有解决您将WordSentence 的类定义放在哪里的基本问题。先解决这个问题,然后所有其他问题都会消失。

标签: c++ linked-list operator-overloading


【解决方案1】:

您收到此错误的原因是,当您转发声明 Sentence 时,您没有向编译器提供生成调用转发声明的类的方法或通过以下方式返回它所需的代码的信息价值。对于前向声明的类,您所能做的就是创建一个指向它的指针。对于其他所有内容,必须有完整的定义。

Word 类的实现文件中包含带有Sentence 类定义的头文件。这将解决这个编译问题。

就实现而言,这一行看起来效率低下:

Sentence *s = new Sentence(sentence.getCopy());

您正在通过将已经是副本的句子传递给复制构造函数来制作另一个副本。这两个替代方案应该也可以正常工作,而无需进行不必要的复制:

Sentence *s = &sentence.getCopy();

Sentence *s = new Sentence(sentence);

当然,这不会消除由于返回动态分配对象的副本而不调用 delete 而导致的内存泄漏。

这样可以避免内存泄漏问题:

Sentence s(sentence);

【讨论】:

  • Sentence s(sentence); 看起来比所有这些选项都好很多,并且避免了内存泄漏。
  • @MattMcNabb 谢谢 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 2021-12-19
  • 2021-03-18
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多