gpt4 book ai didi

c++ - 数组声明和大小初始化(C++)

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:19:36 24 4
gpt4 key购买 nike

我不太确定如何提出这个问题,所以我将从一些示例代码开始:

//header file
class A
{
public:
A();
private:
int x;
std::string arr[x];
}

//cpp file

class A
{
public:
A()
{
/*code to get the value of x from a cmd call*/
}
}

此代码有效吗?更具体地说,我是否可以让我的头文件中的字符串数组的大小为 x,即使在创建 A 对象之前没有专门为 x 指定值?

如果这不起作用,我唯一的选择是使用动态分配的数组吗?

最佳答案

代码无效。您应该改用 vector 。

class A
{
public:
A();
private:
int x;
std::vector<std::string> arr;
};

A::A () : x(command_gets_x()), arr(x) {}

由于 arr 是由 x 的值初始化的,因此构造函数仅在 xarr 之前工作在 A 中(因为它在您的定义中)。但是,如果 x 的唯一目的是跟踪数组的大小,则没有必要,因为 vector 具有 size() 方法。

class A
{
public:
A() : arr(command_gets_x()) {}
int x () const { return arr.size(); }
//...
private:
std::vector<std::string> arr;
};

关于c++ - 数组声明和大小初始化(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11750347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com