【发布时间】: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 定义的位置
-
在类之外定义这个操作符是在这种情况下要走的路,可能通过友元声明或实用函数来辅助。为什么它不起作用?不知道,你肯定是搞错了,但是不看代码也说不准(当然是简化为最小的例子)。
-
您似乎已经发布相同的代码好几天了,但仍然没有解决您将
Word和Sentence的类定义放在哪里的基本问题。先解决这个问题,然后所有其他问题都会消失。
标签: c++ linked-list operator-overloading