基类的代码是
class base
{
public:
	base(int id);
	base(){};
	virtual void toString();
protected:
	int id;
};
base::base(int n)
{
	printf("base constructor!\n");
	id = n;
}
void base::toString()
{
	cout<<"my id is "<<id<<endl;
}
class derive:public base
{
public:
	derive(int id);
};
derive::derive(int n)
{
	printf("derive constructor!\n");
}
这样就隐式调用了基类无参数的构造函数base()。这里要注意,如果派生类的构造函数是上面那样,而基类又没有无参数的构造函数,那么就会 产生编译错误。
就是说,派生类构造函数如果没有显式调用基类的构造函数,那么就会自动隐式调用基类的无参数的构造函数。
测试代码
derive dd(6); dd.toString();
输出结果是
without para,base constructor! derive constructor! my id is 0
如果把基类的无参数的构造函数给去掉,那么就会产生编译错误。
../src/CTest.cpp: 在构造函数‘derive::derive(int)’中: ../src/CTest.cpp:43:21: 错误: 对‘base::base()’的调用没有匹配的函数 ../src/CTest.cpp:43:21: 附注: 备选是: ../src/CTest.cpp:25:1: 附注: base::base(int) ../src/CTest.cpp:25:1: 附注: 备选需要 1 实参,但提供了 0 个 ../src/CTest.cpp:9:7: 附注: base::base(const base&) ../src/CTest.cpp:9:7: 附注: 备选需要 1 实参,但提供了 0 个 make: *** [src/CTest.o] 错误 1
派生类构造函数实现二
derive::derive(int n):base(n)
{
	printf("derive constructor!\n");
}
这样显示调用了基类的构造函数base(n)。
验证代码
derive dd(6); dd.toString();
base constructor! derive constructor! my id is 6
而不能在函数体内调用。
参考资料:
http://www.cnblogs.com/krisdy/archive/2009/06/11/1501390.html
原文地址:http://blog.csdn.net/lingerlanlan/article/details/24721321