C++ 类继承vector<A>

 面向对象程序设计中最重要的一个概念是继承。继承允许我们依据另一个类来定义一个类,这使得创建和维护一个应用程序变得更容易。这样做,也达到了重用代码功能和提高执行效率的效果。

当创建一个类时,您不需要重新编写新的数据成员和成员函数,只需指定新建的类继承了一个已有的类的成员即可。这个已有的类称为基类,新建的类称为派生类

C++可以实现Vector向量的继承,实例如下:


#include <string>
#include <memory>
#include<vector>
#include <iostream>
using namespace std;
int i = 0, j = 0;
class A {
public:
	A(int i) {
		str = to_string(i);
		cout << "构造函数" << ++i << endl;
	}
	~A() { cout << "析构函数" << ++i << endl; }
	A(const A& a) : str(a.str) {
		cout << "拷贝构造" << ++j << endl;
	}
public:
	string str;
};


class intvector :public vector<A> {
public:
	intvector() = default;
	~intvector() { cout << "析构" << endl; }
};


int main() {
	intvector examp;
	examp.emplace_back(10);
	for (int p = 0; p < int(examp.size()); p++) {
		cout << examp[p].str<< endl;
	}
}

输出:

构造函数1
10
析构
析构函数2

再谈构造和析构
当创建一个子类对象时
构造时,先调用父类的构造函数,再调用子类的构造函数
析构时,先调用子类的析构函数,再调用父类的构造函数

如果父类有多个构造函数时,可以显式的调用其中一个
如果没有显式的调用时,默认调用了默认构造函数。

猜你喜欢

转载自blog.csdn.net/qq_23981335/article/details/122339830