如何使用指向动态数组的静态指针创建类?
How to create a class with a static pointer to a dynamic array?
我想定义一个类,它包含一个指向动态数组的静态指针,看起来像
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
相关文章:
- 如何在类内部使用和访问静态指针到成员值s_ptm?
- C++ 返回指向函数内定义的静态数组的指针是否有效?
- decltype:使用指针访问类的静态成员
- 类的静态结构指针声明在C++
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- 指向重载静态成员的函数指针 - 在unique_ptr中用作自定义删除器
- 指向模板上下文中的成员函数或静态函数的指针
- 指向 POD 类型的指针之间的静态转换与重新解释转换
- C++:如何返回指向非静态成员函数的指针?
- 获取具有静态局部变量的绑定/推断捕获 lambda 的函数指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- 函数指针静态,构造函数
- 是否通过单元化指针UB访问静态类成员
- 静态对象指针
- 如何使用指向动态数组的静态指针创建类?
- 静态指针指向这个为mock for googletest定义的类内部
- 为静态类创建指向对象的指针是否合法?
- 指向无静态方法的指针静态方法
- 如何将原始指针静态化为指向固定数组的指针
- 显式销毁非指针静态对象