在项目中,发现很多子类调用父类构造函数的情况,现在特地来熟悉一下:
- #include <iostream>
- using namespace std;
-
- class A
- {
- public:
- int a;
- int b;
-
- public:
- A():a(0), b(0)
- {
- cout << "default A constructor" << endl;
- }
-
- A(int x, int y):a(x), b(y)
- {
- cout << "A constructor" << endl;
- }
- };
-
- class B : public A
- {
- public:
- int c;
-
- public:
- B():A(), c(0)
- {
- cout << "default B constructor" << endl;
- }
-
- B(int x, int y, int z):A(x, y), c(z)
- {
- cout << "B constructor" << endl;
- }
- };
-
- int main()
- {
- B b1;
- cout << b1.a << endl;
- cout << b1.b << endl;
- cout << b1.c << endl;
-
- B b2(1, 2, 3);
- cout << b2.a << endl;
- cout << b2.b << endl;
- cout << b2.c << endl;
-
- return 0;
- }