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

时间:2012-07-31 23:10:11

标签: c++ arrays header size declaration

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

//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没有专门给出值吗?

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

5 个答案:

答案 0 :(得分:5)

代码无效。你应该使用矢量。

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

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

由于arr的初始值为x,因此只有当x位于arr A之前时,构造函数才有效(因为它在您的身上)定义)。但是,如果x的唯一目的是跟踪数组的大小,则没有必要,因为vector具有size()方法。

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

答案 1 :(得分:3)

无效。数组大小必须是常量表达式。是的,您必须使用动态分配,但不一定是直接分配。你可以使用std :: vector。

答案 2 :(得分:2)

不,这是不可能的,因为一个C ++没有可变长度数组,而且,数组大小必须是编译时常量。

您可以在构造函数中使用new分配数组,或者更好地使用std::vector

答案 3 :(得分:1)

不,您无法使用非const表达式初始化数组。这将有效,并且接近您原来的意图:

class A
{
   ...
   const int x = 3;
   std::string arr[x];
};

在.cpp文件中:

int A::x;

答案 4 :(得分:0)

我发现在我的Mac上,在x-code中我可以执行以下操作

int x = foo() // get some value for x at runtime
int array[ x ];

但这是非常不酷的!我昨天刚读过一些编译器允许在堆栈上进行动态分配,但我建议你保持清醒。

如果直到运行时才知道x的值,那么在运行时之前不能分配大小为x的数组。想想编译器的作用:如果我们不知道x有多大,可以分配大小为x的数组吗?唯一剩下的选择是在运行时分配(也称为动态分配)。