我在c ++中尝试使用static关键字。以下类有一个名为size的静态变量,初始化为10.
class staticTest
{
public:
static int size;
int x,y;
staticTest()
{
x=0;
y=0;
}
void display()
{
printf("%d %d\n",x,y);
}
};
int staticTest::size=10;
现在我有另一个使用这个静态变量的类。这是另一个班级
class my
{
public:
int a[staticTest::size];
my()
{
for(int i=0;i<staticTest::size;i++)
{
a[i]=i;
}
}
void display()
{
for(int i=0;i<staticTest::size;i++)
{
printf("%d\n",a[i]);
}
}
};
现在我有这样的主要功能
main()
{
my ni;
ni.display();
}
我无法编译此程序。错误是数组绑定不是整数常量。为什么会这样?
答案 0 :(得分:3)
只有编译时常量可以用作数组大小。
将整数声明为static const int
。
此外,(默认)值需要在声明中,而不是定义:
// in header
class Foo {
public:
static const int n = 10;
};
// in implementation
const int Foo::n;
根据您的评论,请考虑以下事项:目前,您正在有效地使用全局变量来传达一些动态数量。这应该敲响警钟:
int size; // global
void some_UI_function(); // modifies `size`?!
void some_computation()
{
int data[size]; // pseudo-code
// ...
}
由于各种原因,这是一种糟糕的设计。相反,您应该将相关大小的一部分作为该类的一部分:
class my
{
std::vector<int> m_data;
public:
my(std::size_t n) : m_data(n) { }
// ...
};
现在,您可以在本地传达所需的大小:
int main()
{
size_t n = get_data_from_user();
my x(n);
x.compute(); // etc.
}
答案 1 :(得分:2)
数组是静态的,这意味着它们的大小是在编译时设置的。 因此,您需要使用整数常量来声明一个数组。
答案 2 :(得分:1)
在类定义中使用static
关键字并不意味着变量不会更改,而是整个类都有一个变量副本(而不是每个实例都有一个副本)。再加上你只能在编译时使用已知值作为数组大小这一事实,就会给你错误。
您可以通过将size
更改为const
并为其指定值来修复编译错误:
static const int size = 5; // 5 for instance
然而,当你试图获取该变量的地址时会发生奇怪的事情,因为它实际上并不存在于 1 的任何地方,所以不是这样,首选的方法是将其放入你的定义:
static const int size;
然后在一个实现(.cpp
)文件中,定义:
static const int staticTest::size = 5;
1 它可能看起来不像,但这个变量只有一个定义,没有声明。在一些编译器中,它可能会起作用,它们只会在与它所代表的数字一起使用的地方替换该变量,但它是未定义的行为,并且在其他行为中将无法链接,因此不要指望它(正如James所指出的那样) Kanze在评论中。)
答案 3 :(得分:1)
这是因为您的静态变量可以在程序的持续时间内更改值,如果您添加const
限定符,那么static const int size = 10;
它应该按预期工作。
答案 4 :(得分:1)
static关键字指定变量具有静态持续时间(在程序开始时分配,在程序结束时分配)。
只有编译时常量可以用作数组大小。 将您的大小声明为静态常量,同时请注意默认值必须在声明中,而不是在definatio
中根据你的评论使用动态决定数组的大小----
当已知所需的数组大小时,使用new运算符为其分配内存,并将该内存的地址保存在指针中。请记住:指针可以像数组一样下标。下面的示例读入一个数字并分配该大小数组。
int* a = NULL; // Pointer to int, initialize to nothing.
int n; // Size needed for array
cin >> n; // Read in the size
a = new int[n]; // Allocate n ints and save ptr in a.
for (int i=0; i<n; i++) {
a[i] = 0; // Initialize all elements to zero.
}
. . . // Use a as a normal array
delete [] a; // When done, free memory pointed to by a.
a = NULL; // Clear a to prevent using invalid memory reference.
答案 5 :(得分:0)
static 关键字指定变量具有静态持续时间(在程序开始时分配,在程序结束时取消分配)。
括号[]中的元素字段表示数组要保存的元素数,必须是常量值,因为数组是非动态内存块,其大小必须在执行前确定。为了创建具有可变长度的数组,需要动态内存。