如何在Visual Studio C ++中创建对象数组 [英] How to create array of objects in Visual Studio C++

查看:502
本文介绍了如何在Visual Studio C ++中创建对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含设置参数的类。我想创建一个这个参数的数组。


这是类:


ref class Global_Params_Struct

  {

   public:


           ...参数


公开:


          ...方法


}


在"Form1"类中:


公共引用类Form1:public System :: Windows :: Forms :: Form

  {


    公众:

               Form1(无效)

              {

                  
for(Byte i = 0; i< 10; i ++)


  &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; this-> Global_Params_Array [i] = gcnew Global_Params_Struct;

  &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }


  &NBSP;&NBSP; private:array< Global_Params_Struct ^> ^        Global_Params_Array;


}


此代码编译正确,但由于'for'循环的内部行而产生异常:


System.NullReferenceException:'对象引用未设置为对象的实例。'


我应该如何创建' Global_Params_Struct'类的数组?


解决方案

嗯,我认为答案是应该在'for'循环之前添加这一行:


< p style =""> this-> Global_Params_Array = gcnew数组< Global_Params_Struct ^>(ARR_SIZE);


现在程序正在运行。


I have a class contains settings parameters. I want to create an array of this parameters.

This is the class:

ref class Global_Params_Struct
 {
  public:

           ...parameters

public:

          ... methods

}

In class 'Form1':

public ref class Form1 : public System::Windows::Forms::Form
 {

     public:
               Form1(void)
              {
                   for(Byte i = 0; i < 10; i++)
                        this->Global_Params_Array[i] = gcnew Global_Params_Struct;
              }

     private: array<Global_Params_Struct^>^       Global_Params_Array;

}

This code is compiled correctly, but an exception arises due to the internal line of the 'for' loop:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

How should I create an array of 'Global_Params_Struct' class?

解决方案

Well, I think the answer is that this line should be added before the 'for' loop:

this->Global_Params_Array = gcnew array<Global_Params_Struct^>(ARR_SIZE);

Now the program is running.


这篇关于如何在Visual Studio C ++中创建对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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