C++ Overloading operator << for child classes

孤街醉人 提交于 2020-04-13 17:16:20

问题


I have created a class Location which is a parent class for classes Village and City. I have a vector<Location*>, which contains villages and cities. Now, I need to print to the standard output the content of this vector. This is easy:

    for (int i = 0; i < locations.size(); i++)
       cout << locations.at(i);

I have overloaded operator << for classes Village, City and Location. It is called overloaded operator << from class Location all the time. I need to call overloaded operator for Village and City (depends on specific instance). Is there something similar like virtual methods for overloading operators?

I'm new in programming in C++, I'm programming in Java, so please help me. Thanks in advance.


回答1:


Short answer

No, there is no such thing. You can use existing C++ features to emulate it.

Long answer

You can add a method to Location virtual void Print(ostream& os) and implement operator<< like this:

std::ostream& operator<<(ostream& os, const Location& loc) 
{ 
    loc.Print(os); 
    return os; 
}

If you override Print() in your derived classes you will get your desired functionality.




回答2:


Since operator<< can't be a member function (without changing its semantics), you could provide a virtual print method and do double dispatch..

class Location
{
  virtual void print (ostream&);
}

ostream& operator << (ostream& o, Location& l)
{
  l.print(o); // virtual call
  return o;
}


来源:https://stackoverflow.com/questions/23516469/c-overloading-operator-for-child-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!