类的示例数组 [英] Example array of class
本文介绍了类的示例数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何制作类数组?给我一些例子......
How make array of class? Give me some example...
推荐答案
你可以使用数组或指针在堆栈或堆上进行。 Std :: vector是很好的选择。
You can do on stack or heap using arrays or pointers. Std::vector is excellent option.
#include <iostream>
#include <vector>
using namespace std;
class MyClass
{
public:
MyClass() {};
MyClass(const int val) : myVal(val) {};
int getVal() { return myVal;};
private:
int myVal;
};
int main()
{
const int arraySize = 10;
// You can create on stack like so (which is not always a good idea)
MyClass myArray[10];
////////////////////////////////////////////////////////////////////
// Better is to use heap and pointers.
MyClass **classptr = new MyClass *[arraySize];
for(int i = 0; i < arraySize; i++)
classptr[i] = (MyClass *) new MyClass(i);
for(int i = 0; i < arraySize; i++)
cout << classptr[i]->getVal() << endl;
for(int i = 0; i < arraySize; i++)
delete classptr[i];
delete classptr;
//////////////////////////////////
// Or you can use vector
vector <MyClass *> myVector;
for(int i = 0; i < arraySize; i++)
{
MyClass *myClass = new MyClass(i);
myVector.push_back(myClass);
}
for(int i = 0; i < arraySize; i++)
cout << myVector[i]->getVal() << endl;
for(int i = 0; i < arraySize; i++)
delete myVector[i];
}
参考:示例 [ ^ ]
类的数组视频 [ ^ ]。
这篇关于类的示例数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文