使用带参数构造函数继承时注意
来源:互联网 发布: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
- 使用带参数构造函数继承时注意
- 类的继承中带参数的构造函数
- 三角形类的构造函数-使用带参数构造函数
- 带参数的构造函数
- 带参数的构造函数
- Java 带参数构造函数
- 带参数的构造函数
- 带参数的构造函数
- 带参数的构造函数及使用默认参数的构造函数
- C++使用带默认参数的构造函数
- 三角形类(使用带参数构造函数)
- 第五周——使用带参数构造函数
- 第五周 项目一 1.1 使用带参数构造函数
- 使用带参数构造函数求三角形(1)
- 第四周项目1.1 使用带参数构造函数
- 第四周 项目1 使用带参数构造函数
- 三角形类(使用带参数构造函数)
- Fragment使用带参数的构造函数遇到的问题
- Android图片资源获取原则
- HDU 4238 You Are the One
- Intel领投,VR直播公司Voke完成1250万美元A轮融资
- 【LeetCode】
- 怎样理解阻塞非阻塞与同步异步的区别
- 使用带参数构造函数继承时注意
- iOS面试总结(一)
- 数据库连接池
- android View的测量问题
- iOS7以后NavigationBar下的UIScrollView
- 条件高斯分布
- CentOS7.1 KVM虚拟化之虚拟机内存、CPU调整(6)
- C语言冒泡排序
- JVM:内存结构和相关参数