posts - 183,  comments - 10,  trackbacks - 0

继承层次中的输入输出运算符重载

class A
{
};

class B : public A
{
};

方案一
可对 A 进行重载输入输出运算符,然后也对 B 重载相应版本的输入输出运算符

方案二
只对 A 进行重载输入输出运算符,对 A 定义一个 virtual print 函数,在 B 中也对该 virtual 函数 override
在重载的输入输出运算符中调用 virtual print 函数

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 class Complex
 6 {
 7 protected:
 8 // private:
 9     int nR;
10     int nI;
11 public:
12     Complex(int tmpR = -100int tmpI = -100);
13     virtual void display();
14     virtual ostream& print(ostream& os) const;
15     friend ostream& operator << (ostream&const Complex&);
16 };
17 
18 class NameComplex : public Complex
19 {
20 private:
21     string strName;
22 public:
23     NameComplex(const string& = "abc"int = -100int = -100);
24     virtual void display();
25     virtual ostream& print(ostream& os) const;
26     // friend ostream& operator << (ostream&, const NameComplex&);
27 };
28 
29 Complex::Complex(int tmpR, int tmpI) : nR(tmpR), nI(tmpI) {}
30 
31 void Complex::display()
32 {
33     cout << nR << endl;
34     cout << nI << endl;
35 }
36 
37 ostream& Complex::print(ostream& os) const
38 {
39     os << nR << ' ' << nI;
40     return os;
41 }
42 
43 /*
44 ostream& operator << (ostream& os, const Complex& rhs)
45 {
46     os << rhs.nR << ' ' << rhs.nI;
47     return os;
48 }
49 */
50 
51 ostream& operator << (ostream& os, const Complex& rhs)
52 {
53     return rhs.print(os);
54 }
55 
56 NameComplex::NameComplex(const string& str, int nR, int nI) : Complex(nR, nI), strName(str) {}
57 
58 void NameComplex::display()
59 {
60     cout << strName << endl;
61     Complex::display();
62 }
63 
64 /*
65 ostream& operator << (ostream& os, const NameComplex& rhs)
66 {
67     os << rhs.strName << ' ';
68     operator << (os, static_cast<Complex>(rhs));
69     return os;
70 }
71 */
72 
73 ostream& NameComplex::print(ostream& os) const
74 {
75     os << strName << ' ';
76     return Complex::print(os);
77 }
78 
79 int main()
80 {
81     Complex a;
82     cout << a << endl;
83     
84     NameComplex b;
85     cout << b << endl;
86 }

http://topic.csdn.net/u/20110627/22/c4c0b809-13f4-482d-aa26-5faf5c1fc0f0.html?54375

posted on 2011-06-27 23:44 unixfy 阅读(229) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理