这是超载ostream& operator<<
派生类,而无需复制代码的基础类的唯一方法是什么?这些演员是不是应该避免的事情?超载的std :: ostream的&运算<<在派生类而不的static_cast <>
我没有看到任何其他方式,除了在基类中定义某种类型的函数,它将代表基类的数据,因为std :: operator < <可能“吃掉”了字符串?),为派生类执行相同的操作(当然,在派生类流中调用基类流表示函数。
什么是解决这个问题的理想解决方案?
#include <iostream>
class Base
{
private:
int b_;
public:
Base()
:
b_()
{};
Base (int b)
:
b_(b)
{};
friend std::ostream& operator<<(std::ostream& os, const Base& b);
};
std::ostream& operator<< (std::ostream& os, const Base& b)
{
os << b.b_;
return os;
}
class Derived
:
public Base
{
private:
int d_;
public:
Derived()
:
d_()
{};
Derived (int b, int d)
:
Base(b),
d_(d)
{};
friend std::ostream& operator<<(std::ostream& os, const Derived& b);
};
std::ostream& operator<< (std::ostream& os, const Derived& b)
{
os << static_cast<const Base&>(b) << " " << b.d_;
return os;
}
using namespace std;
int main(int argc, const char *argv[])
{
Base b(4);
cout << b << endl;
Derived d(4,5);
cout << d << endl;
return 0;
}
您的解决方案有什么问题? –
@ K-ballo他想避免我想的演员阵容。虽然它没有问题。 –
@Seth Carnegie:为什么?演员出了什么问题?如何调用'operator <<'作为'Base'? –