创建一个数组,可以容纳C ++中不同类的对象 [英] creating an array which can hold objects of different classes in C++
本文介绍了创建一个数组,可以容纳C ++中不同类的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何创建一个可以容纳C ++中不同类对象的数组?
How can I create an array which can hold objects of different classes in C++?
推荐答案
如果要创建自己的,请使用模板和运算符重载包装对指针/数组的访问.下面是一个小例子:
If you want to create your own, wrap access to a pointer/array using templates and operator overloading. Below is a small example:
#include <iostream>
using namespace std;
template <class T>
class Array
{
private:
T* things;
public:
Array(T* a, int n) {
things = new T[n];
for (int i=0; i<n; i++) {
things[i] = a[i];
}
}
~Array() {
delete[] things;
}
T& operator [](const int idx) const {
return things[idx];
}
};
int main()
{
int a[] = {1,2,3};
double b[] = {1.2, 3.5, 6.0};
Array<int> intArray(a, 3);
Array<double> doubleArray(b, 3);
cout << "intArray[1]: " << intArray[1] << endl;
}
这篇关于创建一个数组,可以容纳C ++中不同类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文