重载基类及其派生类(C++)的输出运算符
Overloading the output operator for both the base class and its derived class (C++)
这是一个关于在C++中重载输出运算符的问题:如何使<lt;在基类和派生类上?示例:
#include <iostream>
#include <cstdlib>
using namespace std;
class Base{
public:
virtual char* name(){ return "All your base belong to us.";}
};
class Child : public Base{
public:
virtual char* name(){ return "All your child belong to us.";}
};
ostream& operator << (ostream& output, Base &b){
output << "To Base: " << b.name() ;
return output;}
ostream& operator << (ostream& output, Child &b){
output << "To Child: " << b.name() ;
return output;}
int main(){
Base* B;
B = new Child;
cout << *B << endl;
return 0;
}
输出为
To Base: All your child belong to us."
所以Child中的name()在Base中的后面;但是<lt;不会从Base下降到Child。我怎么能超载<lt;使得当其参数在Base中时,其仅使用<lt?
我想在这种情况下输出"致孩子:你所有的孩子都属于我们"。
使其成为一个虚拟函数。
class Base{
public:
virtual const char* name() const { return "All your base belong to us.";}
inline friend ostream& operator<<(ostream& output, const Base &b)
{
return b.out(output);
}
private:
virtual ostream& out(ostream& o) const { return o << "To Base: " << name(); }
};
class Child : public Base{
public:
virtual const char* name() const { return "All your child belong to us.";}
private:
virtual ostream& out(ostream& o) const { return o << "To Child: " << name(); }
};
int main(){
Base* B;
B = new Child;
cout << ( Child &) *B << endl;
return 0;
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 输出没有重复元素的动态数组(收缩数组)C++
- 如何根据单词在文本中出现的概率输出单词