简体   繁体   English

C ++重载运算符<<用于子类

[英]C++ Overloading operator << for child classes

I have created a class Location which is a parent class for classes Village and City . 我创建了一个Location类,它是VillageCity类的父类。 I have a vector<Location*> , which contains villages and cities. 我有一个vector<Location*> ,其中包含村庄和城市。 Now, I need to print to the standard output the content of this vector . 现在,我需要将此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 . 我对VillageCityLocation类的运算符<<过载。 It is called overloaded operator << from class Location all the time. 它一直被称为Location类中的重载运算符<<。 I need to call overloaded operator for Village and City (depends on specific instance). 我需要为VillageCity调用重载运算符(取决于特定实例)。 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. 我是C ++编程的新手,我是Java编程的人,所以请帮助我。 Thanks in advance. 提前致谢。

Short answer 简短答案

No, there is no such thing. 不,没有这样的事情。 You can use existing C++ features to emulate it. 您可以使用现有的C ++功能进行仿真。

Long answer 长答案

You can add a method to Location virtual void Print(ostream& os) and implement operator<< like this: 您可以将一个方法添加到Location virtual void Print(ostream& os)并实现operator<<如下所示:

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. 如果在派生类中重写Print() ,则将获得所需的功能。

Since operator<< can't be a member function (without changing its semantics), you could provide a virtual print method and do double dispatch.. 由于operator<<不能是成员函数(在不更改其语义的情况下),因此您可以提供虚拟print方法并进行两次分派。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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