這是超載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'? –