简体   繁体   中英

c++ operator overloading << on Array pointers

I have two classes, Pony and Bear which inherits from an Animal Abstract Class.

I have made an Animal Array which contains one Pony and one Bear :

Animal **arr = new Animal * [2];
arr[0] = new Pony("pony name");
arr[1] = new Bear("bear name");

The argument to Pony and Bear is it name. I then want to print the Animal name by ovearloading the << operator. something like

cout << arr[0];  // Print something like : "I am Pony/Bear Name !"

But my test to overload fail... I try to do something like

ostream & operator<<(ostream& os, Animal &a);

But It do not detect the overload when I compile...

How is it possible to overload the << operator in my array of pointers ?

Full error after the test *arr[0]

main.cpp: In function ‘Object** MyUnitTests()’:
main.cpp:20:22: error: no match for ‘operator<<’ in ‘std::cout << * * obj’
main.cpp:20:22: note: candidates are:
In file included from /usr/include/c++/4.7/iostream:40:0,
             from Object.hh:14,
             from main.cpp:11:

And then 200 lines of errors comming from std::cout (they disapears if I remove the * on the arr[0]).

arr[0] is a pointer, so you'll need to perform indirection to be able to pass it to that operator<< overload:

cout << *arr[0];

You're using new much more than you should be. I'll let you off with the animals themselves because you need polymorphism (although you should use smart pointers instead), but the array of pointers does not need to be dynamically allocated:

Animal* arr[2];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM