- //============================================================================
- // Name : main.cpp
- // Author : sg131971
- // Version :
- // Copyright : sg131971@qq.com
- // Description : Hello World in C++, Ansi-style
- //============================================================================
- #include <iostream>
- using namespace std;
- class A
- {
- public:
- A()
- {
- cout << __LINE__ << ": " << "1" << endl;
- }
- virtual ~A()
- {
- cout << __LINE__ << ": " << "2" << endl;
- }
- virtual int Add(int n)
- {
- return 0;
- }
- };
- class B:public A
- {
- public:
- B(int n):num(n)
- {
- }
- virtual ~B()
- {
- }
- virtual int Add(int n)
- {
- num += n;
- return num;
- }
- private:
- int num;
- };
- class C:public A
- {
- public:
- C(A& obj, int n):a(obj), num(n)
- {
- cout << __LINE__ << ": " << "3" << endl;
- }
- virtual ~C()
- {
- cout << __LINE__ << ": " << "4" << endl;
- }
- virtual int Add(int n)
- {
- return a.Add(n + num);
- }
- private:
- A& a;
- int num;
- };
- int main()
- {
- B b(100);
- C c1(b, 1), c2(c1, 2);
- cout << __LINE__ << ": " << c2.Add(50) << endl;
- return 0;
- }
- 17: 1
- 17: 1
- 54: 3
- 17: 1
- 54: 3
- 73: 153
- 58: 4
- 21: 2
- 58: 4
- 21: 2
- 21: 2
本文通过实现一个简单的C++类继承与多态特性实例,详细解析了C++中类的定义、构造函数、析构函数、虚函数以及类之间的继承关系,展示了如何在实际编程中利用这些特性来简化代码结构,提高代码复用性和灵活性。通过创建类B和类C,分别展示了基类和派生类的交互,以及如何在派生类中重写基类的虚函数以实现多态性。
1万+

被折叠的 条评论
为什么被折叠?



