0

So basically I have a class "Sentence" that #includes "Word".

Sentence is a linked list of words

Here's my Question

"Word + Sentence returns a new Sentence with the Word added to the beginning" so basically

Word w = "The";
Sentence s = "dog jumped high."
//the object type of w+s should be a sentence

However, I get the error,

'Sentence' does not name a type
//this is in reference to the return type of overloaded operator+ function, which is in the word class

So is there a way to flip the right hand and left hand sides of the operator+ overload so that I can put the code in the Sentence class.

I can't put the code in the Sentence class because there is a separate overload function where I need

s+w 

to return a sentence with the word added to the end

user3400223
  • 748
  • 5
  • 10
  • 2
    The problem is that you can't declare a function returning `Sentence` until after you have defined the `Sentence` class. To avoid this problem, use non-member operator overloads (which is a good idea anyway). [See here for a full rundown](http://stackoverflow.com/questions/4421706/operator-overloading) – M.M Oct 17 '14 at 00:29
  • Give sentence a non-explicit constructor which takes a word to create a 1 word sentence. Now you only need one non-member operator+ taking two sentences, and you can pass words to it too. – Neil Kirk Oct 17 '14 at 00:30
  • @MattMcNabb: That is incorrect. You can declare a function returning `Sentence` as long as `Sentence` is declared. No definition for `Sentence` is required unless you are also defining the function. – Dietrich Epp Oct 17 '14 at 00:34

1 Answers1

4

In C++, operators do not have to be members at all. So just define the operator outside of your classes:

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

Also note that you can forward declare classes:

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 {
    ...
}
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • The whole operator+ approach is going to be slow, copying linked lists of strings millions of times. Let it go. – Neil Kirk Oct 17 '14 at 00:36
  • I should note that my classes are all separated by headers and implementation files. So I tried both ways. The first way keeps giving me an error saying that the function is already defined in other places. The other gives me an error saying how the the class Sentence is incomplete. I've been trying to solve there errors for a couple hours now. – user3400223 Oct 19 '14 at 00:41
  • @user3400223: That's not really enough to understand what is going on. I suggest asking another question, with code snippets and error messages. – Dietrich Epp Oct 19 '14 at 00:44