对于构造函数初始化,分为有参数构造函数初始化和无参数构造函数初始化。
1、无参数构造函数初始化
SubBase obj1; 这里对象 obj1 无参数带入,但是构造函数需要初始化,这时只能先在 SubBase 类中调用无参数构造函数 SubBase(){z=0;},然后在调用父类中无参数构造函数 Base();Base::Base(){x=0;y=0;} 这样 x,y,z 分别都被初始化为 x=0,y=0,z=0. 下面调用 obj1.display(); 时就会份别输出 x=0,y=0,z=0
调用无参数 SubBase obj1; 构造函数初始化顺序如下:
- SubBase() {
- z = 0;
- }
- Base();
- Base: :Base() {
- x = 0;
- y = 0;
- }
2、有参数构造函数初始化
- SubBase obj2(1, 2, 3);这里对象obj2(1,
- 2,
- 3)为有参数带入。构造函数初始化SubBase(int m, int n, int l);
- SubBase: :SubBase(int m, int n, int l) : Base(m, n),
- z(l) {}
- Base: :Base(int m, int n) : x(m),
- y(n) {}这里初始化为x = m,
- y = nSubBase: :SubBase(int m, int n, int l) : Base(m, n),
- z(l) {}
初始化 x,y 之后,再执行 z(l),z(l) 就等于 z=l
执行完上面几条语句之后,带参数对象的构造函数初始化可以得到
- x = m,
- y = n,
- z = l
后面执行 obj2.display();
可以打印出 x=1,y=2,z=3
总结:(1)对于上面函数 z(l) 就等价于 z=l,x(m) 等价于 x=m,y(n) 等价于 y=n。
(2)对于有参数构造函数的初始化
- SubBase: :SubBase(int m, int n, int l) : Base(m, n),
- z(l) {}
父类中已有的两个参数 x,y 可以通过调用父类的带参数构造函数进行初始化,对于 z,需要在这里单独进行初始化。
源代码:
- #includeusing namespace std;
- class Base {
- int x;
- protected: int y;
- public: Base();
- Base(int m, int n);
- void set(int m, int n);
- int getX();
- int getY();
- void display();
- };
- Base: :Base() {
- x = 0;
- y = 0;
- }
- Base: :Base(int m, int n) : x(m),
- y(n) {}
- void Base: :set(int m, int n) {
- x = m;
- y = n;
- }
- int Base: :getX() {
- return x;
- }
- int Base: :getY() {
- return y;
- }
- void Base: :display() {
- cout << "x = " <
来源: http://www.92to.com/bangong/2016/12-02/13839545.html