C ++重载运算符<<对于儿童班 [英] C++ Overloading operator << for child classes

查看:76
本文介绍了C ++重载运算符<<对于儿童班的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类Location,它是类VillageCity的父类.我有一个vector<Location*>,其中包含村庄和城市.现在,我需要将此vector的内容打印到标准输出中.这很简单:

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);

我运算符<<对于类VillageCityLocation.它称为重载运算符<<始终来自类Location.我需要为VillageCity调用重载运算符(取决于特定实例).是否有类似类似虚拟方法的操作符重载?

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?

我是C ++编程的新手,我是Java的编程,所以请帮助我.预先感谢.

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

推荐答案

简短答案

不,没有这样的东西.您可以使用现有的C ++功能对其进行仿真.

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

好答案

您可以将方法添加到Location virtual void Print(ostream& os)并实现operator<<,如下所示:

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; 
}

如果您在派生类中重写Print(),则将获得所需的功能.

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

这篇关于C ++重载运算符&lt;&lt;对于儿童班的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆