Operator Overloading Question

Hello,
I have a class called Person and one of its members is of type Name (also a class.)

I have overloaded the Name class so that it will work for

 
cout << nameInstance;


But in Person I have a method called getName() which returns a Name. Now if I try do this:

 
cout << personInstance.getName();


I get an error saying:


no match for ‘operator<<’ in ‘std::cout << Person::getName()()’


But also if I do:

1
2
Name n = person.getName();
cout << n;


Then that also works! I can't understand why I'm getting that error. I have checked my "C++ how to program" book and they don't ever seem to try do what I'm doing but I don't see why it shouldn't work...

Could someone please tell me what is going on?

Thanks,
Keith
Can you paste the prototype for Person::getName and operator<< ?
I guess that you have some problem with references
Thanks Bazzy...

This is in Name.h:

 
friend ostream& operator<<(ostream& out, Name& name);


In Name.cpp:

1
2
3
4
5
6
7
8
/**
 * For cout etc.
 */
ostream& operator<<(ostream& out, Name& name) {
	out << name.get();

	return out;
}


And this is in Person.cpp

1
2
3
4
5
6
/**
 * Gets the person's name.
 */
Name Person::getName() {
	return name;
}
Yes, that's the problem.
The second parameter of operator<< must be a const reference
( friend ostream& operator<<(ostream& out, const Name& name); )
This will ensure that a call to operator<< won't modify the object and it will accept temporaries ( such as an object returned by a function )
Last edited on
Perhaps a const-correctness issue? Try passing name by reference to const.

EDIT: Too late...
Last edited on
That done the trick!

Thank you!



And thanks moorecm for taking the time to reply as well!
Topic archived. No new replies allowed.