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

How to create a class with a static pointer to a dynamic array?

本文关键字:指针 静态 创建 数组 何使用 动态      更新时间:2023-10-16

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

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

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

编译时应该初始化静态变量,但是,我没有 知道 n 在这个阶段的值。

以下示例说明了 2 个可用的选项。 此代码编译并运行。

笔记:

1) 类 "MyStruct_t" 使用默认的 CTOR/DTR。

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

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

4) 当没有输入命令行参数(argc <2)时,exec() 调用一个存根函数 "MyStruct_t::d etermine_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

建议如下:

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