这是在ostream& operator<<
不复制基类代码的情况下为派生类重载的唯一方法吗?演员表不是应该避免的吗?
我没有看到任何其他方式,除了在基类中定义某种函数,它将基类的数据表示为 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;
}