如何用静态指针创建指向动态数组的类?

时间:2019-10-27 21:31:37

标签: c++

我想定义一个类,其中包含指向动态数组的静态指针,看起来像

class MyStruct
{
    public:
        static int n;
        static int *pArr;
};

此处,n是动态定义的输入变量。 pArr是指向大小为n的数组的指针。我现在遇到的问题是静态变量应在编译时初始化,但是,在此阶段,我不知道n的值。

2 个答案:

答案 0 :(得分:0)

建议类似

class MyStruct {
   // better have private members
        static int n;
        static int *pArr;
    public:
        static void init(int size) {
           n = size;
           pArr = new int[n]; // must be sure to delete this somewhere
        }
};

// in a .cpp file - must define your static members
int MyStruct::n; // default 0
int* MyStruct::pArr; // default nullptr

答案 1 :(得分:0)

  

静态变量应在编译时初始化,但是,我不   在此阶段知道n的值。

这里是一个示例,说明您可以使用的2个选项。这段代码会编译并运行。

注意:

1)类“ MyStruct_t”使用默认的ctor / dtor。

2)在我的实践中,后缀'_t'区分用户定义的类型。

3)MyStruct_t :: exec()接收argc和argv演示使用命令行参数选择pArr大小。

4)如果未输入任何命令行参数(argc <2),则exec()调用存根函数“ MyStruct_t :: determine_array_size()”。


#include <iostream>
using std::cout, std::endl;

#include <cstdint>

#include <cstdlib>
using std::strtoul;

#include <cassert>


class MyStruct_t
{
   static unsigned long  n;
   static uint* pArr;

public:
   // use default ctor, dtor

   int exec(int argc, char* argv[])
      {
         if (argc > 1)
         {
            // array size passed in as command line parameter
            char* end;
            n = strtoul(argv[1], &end, 10);
            // assert(no range error);
            assert(n > 0); // if no conversion possible, 0 is returned
                           // asserts when user enters 0
         }
         else
         {
            // function to compute array size from tbd
            // see stub below
            n = determine_array_size();
         }

         assert(n > 0); // array size must be positive, i.e. > 0

         // now ok to allocate dynamic array
         pArr = new uint[n];

         // init pArr with uninteresting data, easy to validate
         for (uint i=0; i<n; ++i)
            pArr[i] = i+1;

         // show pArr for validation
         show();

         return 0;
      }

   void show()
      {
         cout << "\n   n:    "  << n << "\n";
         for (uint i=0; i<n; ++i)
            cout << "\n  [" << i << "]    " << pArr[i];
         cout << endl;
      }

private:    
   // stub for debug and code development
   uint determine_array_size()
      {
         // do 'what ever' to figure out array size -
         // prompt? read a file? count something? etc.
         return 5;
      }

}; // class MyStruct_t

// declare and init static parameters
unsigned long MyStruct_t::n    = 0;
uint*         MyStruct_t::pArr = nullptr;


int main(int argc, char* argv[])
{
   MyStruct_t myStruct;  // instantiate object

   return myStruct.exec(argc, argv); // use it
}

没有命令行参数时输出

   n:    5

  [0]    1
  [1]    2
  [2]    3
  [3]    4
  [4]    5

第一个命令行参数为7时输出(忽略其他参数)

   n:    7

  [0]    1
  [1]    2
  [2]    3
  [3]    4
  [4]    5
  [5]    6
  [6]    7
相关问题