简体   繁体   English

c ++中的静态成员

[英]static member in c++

I was experimenting with static keyword in c++. 我在c ++中尝试使用static关键字。 The following class has a static variable called size which is initialized as 10. 以下类有一个名为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;

Now i have another class which uses this static variable. 现在我有另一个使用这个静态变量的类。 Here is the other class 这是另一个班级

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]);
                }
            }
};   

Now i have main function like this 现在我有这样的主要功能

main()
{
    my ni;
    ni.display();
}

I am unable to compile this program. 我无法编译此程序。 Error is that array bound is not an integer constant. 错误是数组绑定不是整数常量。 Why is this so? 为什么会这样?

Only compile-time constants can be used as array sizes. 只有编译时常量可以用作数组大小。

Declare your integer as static const int . 将整数声明为static const int

Also, the (default) value needs to go in the declaration, not the definition: 此外,(默认)值需要在声明中,而不是定义:

// in header
class Foo {
public:
  static const int n = 10;
};

// in implementation
const int Foo::n;

Based on your comment, consider this: At the moment, you are effectively using a global variable to communicate some dynamic quantity. 根据您的评论,请考虑这一点:目前,您正在有效地使用全局变量来传达一些动态数量。 This should ring alarm bells: 这应该响起警钟:

int size; // global

void some_UI_function(); // modifies `size`?!

void some_computation()
{
  int data[size]; // pseudo-code
  // ...
}

This is terrible design, for a whole range of reasons. 由于各种原因,这是一种糟糕的设计。 Instead, you should make the relevant size part of the class: 相反,您应该使相关大小成为该类的一部分:

class my
{
  std::vector<int> m_data;
public:
  my(std::size_t n) : m_data(n) { }
  // ...
};

Now you can communicate the desired size locally: 现在,您可以在本地传达所需的大小:

int main()
{
  size_t n = get_data_from_user();
  my x(n);
  x.compute(); // etc.
}

Arrays are static, which means that their size is being set at compile time. 数组是静态的,这意味着它们的大小是在编译时设置的。 Therefore, you need to use integer constants to declare an array. 因此,您需要使用整数常量来声明数组。

The static keyword when used inside a class definition does not mean that the variable won't change, but that the entire class has one copy of the variable (instead of each instance having a copy). 在类定义中使用static关键字并不意味着变量不会改变,而是整个类都有一个变量副本(而不是每个实例都有一个副本)。 That, coupled with the fact that you can only use values known at compile time as an array size, is what's giving you your error. 再加上你只能在编译时使用已知值作为数组大小的事实,就会给你带来错误。

You can fix the compile error by changing size to const and giving it a value: 您可以通过将size更改为const并为其赋值来修复编译错误:

static const int size = 5; // 5 for instance

However, weird things can start happening when you try to take the address of that variable since it doesn't really exist anywhere 1 , so instead of that, the preferred method is to have this in your definition: 但是,当你尝试获取该变量的地址时会发生奇怪的事情,因为它实际上并不存在于任何地方1 ,所以首选的方法是在你的定义中使用它:

static const int size;

And then in one implementation ( .cpp ) file, have the definition: 然后在一个实现( .cpp )文件中,定义:

static const int staticTest::size = 5;

1 It may not look like it, but this variable only has a definition and no declaration. 1它可能看起来不像,但这个变量只有一个定义而没有声明。 In some compilers it may work, where they will just substitute that variable in places it is used with the number it represents, but it's undefined behaviour and will fail to link in others, so don't count on it (as pointed out by James Kanze in the comments). 在一些编译器中,它可能会起作用,它们只会在与它所代表的数字一起使用的地方替换该变量,但它是未定义的行为,并且在其他行为中将无法链接,因此不要指望它(正如James所指出的那样) Kanze在评论中)。

That is because your static variable can change value during the duration of your program, if you add the const qualifier, like so static const int size = 10; 这是因为你的静态变量可以在程序的持续时间内改变值,如果添加const限定符,就像static const int size = 10; it should work as expected. 它应该按预期工作。

The static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends). static关键字指定变量具有静态持续时间(在程序开始时分配,在程序结束时分配)。

Only compile-time constants can be used as array sizes. 只有编译时常量可以用作数组大小。 declare your size as static constant, also note that default value must go in declaration, not in definatio 将您的大小声明为静态常量,同时请注意默认值必须在声明中,而不是在definatio中


for dynamic deciding the size of array as per ur comment use---- 根据你的评论使用来动态决定数组的大小----

When the desired size of an array is known, allocate memory for it with the new operator and save the address of that memory in the pointer. 当已知所需的数组大小时,使用new运算符为其分配内存,并将该内存的地址保存在指针中。 Remember: Pointers may be subscripted just as arrays are. 请记住:指针可以像数组一样下标。 The example below reads in a number and allocates that size array. 下面的示例读入一个数字并分配该大小数组。

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.

The static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends). static关键字指定变量具有静态持续时间(在程序开始时分配,在程序结束时分配)。

The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution . 括号[]中的元素字段表示数组要保存的元素数,必须是常量值,因为数组是非动态内存块,其大小必须在执行前确定 In order to create arrays with a variable length dynamic memory is needed. 为了创建具有可变长度的数组,需要动态存储器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM