What are best practices when overloading the << operator. Particularly, how do I distinguish between opearting on a pointer vs an object. Is it kosher for them to both output the same string when fed to <<?

For instance, consider the following code where both Book objects have been initialized

Book b1;
Book* b2;

// initialization stuff

// can both of these output the same representation of a book object?
cout << b1 << endl;
cout << b2 << endl;
有帮助吗?

解决方案

how do I distinguish between opearting on a pointer vs an object.

By the signature of the operator<< function:

std::ostream& operator<<(std::ostream&, const Book&); // operates on object
std::ostream& operator<<(std::ostream&, const Book*); // operates on pointer

Is it kosher for them to both output the same string?

It is allowed, but not particularly useful. It is very rare to see the second form implemented. If you are tempted to implement the second form, realize that it is entirely redundant. For example, if you have a Book* pBook:

std::cout << *pBook << "\n";

That will print the object to which pBook points quite nicely.

其他提示

Don't overload operator<< for pointers-to-T. Instead, overload for T itself (or rather, const T& as appropriate), and dereference the pointer in your call to operator<<.

cout << *b2 << endl;

Overloading for pointer-to-T will just create confusion and potentially name collisions, and isn't necesarry in the first place if you overload for const T&

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top