使用带参数构造函数继承时注意

来源:互联网 发布:profili软件 编辑:程序博客网 时间:2024/05/17 09:23

基础:
1. 纯虚类无法实例化!(含有纯虚函数的类称为纯虚类)
2. 虚函数不可只声明不定义!(普通类方法可以只声明)


先举一个例子,方便描述:

#include<iostream>using namespace std;class CTest {public:CTest() { cout << "default constructor." << endl; };~CTest() { cout << "destructor." << endl; };};int main(){CTest l_oTest;return 0;}
当虚类作为父类时 (同虚继承),若构造函数CTest()变为(即默认构造函数删除)带参的构造函数
CTest(int a) { cout << "constructor - with param" << endl; }
此时使用CTest类定义对象时应该如下:
CTest l_oTest(2);  // 此时缺少默认构造函数,必须赋参数

接下来,定义一个CTest的子类:

class CSubTest : public CTest {CSubTest(int a) { cout << "CSubTest's constructor" << endl; }~CSubTest() { cout << "CSubTest's destructor." << endl; }};
此时使用CSubTest类时会报错:
CSubTest l_oTest(2);error C2512: 'CTest' : no appropriate default constructor available// "CTest"类没有默认构造函数
但是难道非要在带参数构造函数的基础上添加默认构造函数吗?
显式调用带参数的构造函数,就可以。
CSubTest(int a):CTest(a) { cout << "constructor - with param" << endl; }
如上调用,则可以调用父类CTest(int a)的构造函数。


最终程序:

#include<iostream>using namespace std;class CTest {public:CTest(int a) { cout << "constructor - with param" << endl; }~CTest() { cout << "destructor." << endl; }};class CSubTest : public CTest {public:CSubTest(int a):CTest(a) {cout << "constructor - with param" << endl; }~CSubTest() { cout << "destructor." << endl; }};int main(){    CSubTest l_oTest(2);return 0;}


0 0