如何使用参数声明自定义c ++类的对象数组 [英] how to declare an array of objects for custom c++ class with parameter

查看:284
本文介绍了如何使用参数声明自定义c ++类的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的c ++程序中,类声明部分如下:

Hi, in my c++ program, class declarations section are as follows:

class CMain
{
    CMain(int n);
    ~CMain();
};



然后,我想在其他cpp文件中创建此类的动态数组。

例如,as如下所示


And then, I want to create dynamic array of this class in other cpp file.
For instance, as shown below

int* pA = new int [m];



但是我不知道该怎么做,因为构造函数有参数。

谢谢。


But I don't know how to do, because the constructor has parameter.
Thanks.

推荐答案

我找到了你帮助的答案。



Hi, I found the answer by your helps.

class CFeature
{
    int x;
    int y;
    int z;
    CFeature(int x, int y, int z);
...
};







vector<cfeature> pFeature(nCnt, CFeature(100, 200, 0));
</cfeature>





谢谢。



Thanks.


正如_duDE_所建议的,你可以使用标准的库容器来做到这一点。但是我更喜欢使用向量,而不是列表

As suggested by _duDE_, you could do that using a standard library container. However I'd prefer using a vector, instead of a list:
#include <iostream>
#include <vector>
class CMain
{
  int n;
public:
    CMain(int n):n(n){}
    int get() const {return n;}
    ~CMain(){}
};

int main()
{
  int n;
  std::cout << "ho many items? " << std::endl;

  std::cin >> n;

  std::vector < CMain > vcm ( n, 5);
  CMain cm(3);
  std::cout << cm.get() << std::endl;


  for (int i=0; i<n; ++i)
    std::cout << "vcm[" << i << "] = " << vcm[i].get() << std::endl;

}





C ++ 11 支持,你需要使用初始化列表:





With C++11 support, you migh use initializer lists:

#include <iostream>
#include <vector>
class CMain
{
  int n;
public:
    CMain(int n):n(n){}
    int get() const {return n;}
    ~CMain(){}
};

int main()
{
  std::vector < CMain > vcm {13, 15, 23, 12};

  for (const auto & cm : vcm )
    std::cout <<  cm.get() << std::endl;
}


尝试使用STL(std :: list)如下:



Try to use the STL (std::list) as follow:

#include "stdafx.h"
#include <iostream>
#include <list>

using namespace std;

class CMain
{
private: 
	int _n;

public:
	CMain(int n){ _n = n; };
	~CMain(){};
};
 

int _tmain(int argc, _TCHAR* argv[])
{
	int n = 4;
	int m = 5;
	list<CMain> * plistCMain = new list<CMain>(m, n);
}





您创建一个包含参数n的类的m实例列表。



You create a list of m - instances of the Class with parameter n.


这篇关于如何使用参数声明自定义c ++类的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆