无论子类有无定义自身的默认构造函数,都会调用父类的默认构造。
如果子类没有定义自身的赋值拷贝函数,会自动调用父类的默认构造。若子类定义了,需通过初始化列表显式调用父类的赋值构造函数。
如果子类没有定义自身的拷贝构造函数,会自动调用父类的拷贝构造函数。若子类定义了,会自动调用父类的默认构造函数。
因此最省事的方法是在初始化列表写上想调用的父类构造函数,不用记忆。
using Base::Base;子类无构造函数时才有用,其实就是指拷贝构造。
class A {
public:
A() { cout << "A ctor" << endl; }
A(int i) { cout << "A para ctor=" << i << endl; }
A(const A& a) { cout << "A copy ctor=" << endl; }
~A() { cout << "A dtor=" << endl; }
};
class B {
public:
B() {cout << "B ctor" << endl; }
//B(double i) { cout << "B para ctor=" << i << endl; }
B(int i) { cout << "B para ctor=" << i << endl; }
B(const B& a) { cout << "B copy ctor=" << endl; }
~B() { cout << "B dtor=" << endl; }
};
class C : public A, public B {
//class C : public B {
public:
//using A::A;
//using B::B; //编译出错,重复定义C(int)
C() { cout << "C ctor" << endl; }
~C() { cout << "C dtor=" << endl; }
// 显式定义继承构造函数 C(int)
C(int i) :A(i), B(i) {}
//C(int c) { cout << "c para ctor=" <<c<< endl; }//注意差别
C(const C& c) { cout << "c copy ctor=" << endl; }
//C(const C&c):A(c),B(c){cout << "c copy ctor=" << endl;}//注意差别
};
void test03() {
C c;
cout<<"======"<<endl;
C c2(2);
cout<<"======"<<endl;
C c3(c2);
cout<<"======"<<endl;
//B b;
cout<<"======"<<endl;
//func(1.0);
}