如何调用继承的重载运算符<<并在派生类的输出中添加更多文本?
How can i call inherited overloaded operator << and add more text in output in derived class?
我有基类Karta和派生类Borac。在类 Karta 中,我重载了运算符 <<,但在派生类 (Borac( 中,我想为基类调用函数运算符<<((,然后在最终输出中添加更多文本。 怎么做?
若要调用特定重载,可以将相应的参数强制转换为该特定重载所需的类型:
struct Base {
};
struct Derived : public Base {
};
std::ostream &operator << (std::ostream & o, const struct Base &b) {
o << "Base;";
return o;
}
std::ostream &operator << (std::ostream & o, const struct Derived &d) {
o << dynamic_cast<const Base&>(d);
o << "Derived;";
return o;
}
int main() {
Derived d;
std::cout << d << std::endl;
}
输出:
Base;Derived;
为了调用基类函数,请指定附加到函数前面的基类名称,类似于命名空间语法:
Type Borac::operator<<() {
Karta::operator<<(); // calls operator<<() of the Karta class on this
// Here goes any additional code
}
假设你的意思是operator<<
std::ostream
,你可以Borac
强制转换为Karta
以使用基类运算符(然后附加任何特定于Borac
的内容(。否则,如果您的运算符是类成员,则可以使用其他答案。
std::ostream& operator<< (std::ostream& os, const Borac& b) {
os << dynamic_cast<const Karta&>(b);
os << "Additional part for Borac";
return os;
}
在线查看
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 呼叫运营商<<临时
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 过载输出<<用于类的运算符,以打印其中的元组
- 重载运算符<<输出地址而不是数据成员
- 什么会导致死亡<<变量& lt; & lt;“ t";当输出超过终端宽度时,打印空白而不是值
- Can运算符<<用于设计我们自己的输出显示方式