先看一个例子:
![](http://static.blog.csdn.net/images/save_snippets.png)
#include <iostream>
class A
{
public:
A() { ::std::cout << "constructor: A" << ::std::endl; } // 构造函数不能为 virtual
A(int aa): a(aa) { ::std::cout << "constructor: A, a = " << a << ::std::endl; }
virtual ~A() { ::std::cout << "destructor: A" << ::std::endl; }
public:
int a;
};
class B : public A
{
public:
B() { ::std::cout << "constructor: B" << ::std::endl; }
B(int bb) : b(bb) { ::std::cout << "constructor: B, b = " << b << ::std::endl; }
B(int aa, int bb): A(aa), b(bb) { ::std::cout << "constructor: B, a = " << a << ", b = " << b << ::std::endl; }
~B() { ::std::cout << "destructor: B" << ::std::endl; }
public:
int b;
};
class A2
{
public:
A2() { ::std::cout << "constructor: A2" << ::std::endl; }
explicit A2(int aa) { ::std::cout << "constructor: A2, aa = " << aa << ::std::endl; }
virtual ~A2() { ::std::cout << "destructor: A2" << ::std::endl; }
};
class B2: public A2
{
public:
using A2::A2; // Inheriting constructors(VS2013 not support, GCC before version 4.8 not support)
~B2() { ::std::cout << "destructor: B2" << ::std::endl; }
};
int main()
{
B b_1; // A() --> B() --> ~B() --> ~A() 隐式调用直接父类的无参构造函数
B b_2(22); // A() --> B(int) --> ~B() --> ~A() 隐式调用直接父类的无参构造函数
B b_3(11, 22); // A(int) --> B(int, int) --> ~B() --> ~A() 委托构造函数
// 其实这里调了 B2() 及 B2(int), 只不过没有输出而已
B2 b2_1; // A2() --> B2() --> ~B2() --> ~A2()
B2 b2_2(11); // A2(int) --> B(int) --> ~B2() --> ~A2()
return 0;
}
/*
constructor: A
constructor: B
constructor: A
constructor: B, b = 22
constructor: A, a = 11
constructor: B, a = 11, b = 22
constructor: A2
constructor: A2, aa = 11
destructor: B2
destructor: A2
destructor: B2
destructor: A2
destructor: B
destructor: A
destructor: B
destructor: A
destructor: B
destructor: A
*/
结论:
1. 构造函数不能为 virtual, 构造函数不能继承;
2. 如果子类不显式调用父类的构造函数,编译器会自动调用父类的【无参构造函数】;
3. 继承构造函数(Inheriting constructors)
(1) C++11 才支持;
(2) 实质是编译器自动生成代码,通过调用父类构造函数来实现,不是真正意义上的【继承】,仅仅是为了减少代码书写量(参考 《C++ Primer》)。
FROM: http://blog.csdn.net/duyiwuer2009/article/details/41047609