如何在 C++ 中为数组声明固定大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8826781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:10:37  来源:igfitidea点击:

How to declare a fixed size for an array in C++

c++

提问by Pincopallino

Quick and stupid question. How do I declare the size for an array if I'm not allowed to use global variables?

快速而愚蠢的问题。如果不允许使用全局变量,如何声明数组的大小?

Suppose I have the file Album.h:

假设我有文件Album.h

class Album {
private:
    Song songs[MAX_SONGS];

    //...

}

where do I put MAX_SONGS = 30? const int MAX_SONGS = 30is considered a variable right? Please notice that the size should be known to the entire program.

我该放在MAX_SONGS = 30哪里? const int MAX_SONGS = 30被认为是一个变量吗?请注意,整个程序应该知道大小。

回答by Armen Tsirunyan

class Album {
private:
    static const int MAX_SONGS = 100;
    Song songs[MAX_SONGS];

    //...
};

Note that inline initialization of static const variables is only allowed for those whose type is integral. Also note that regardless of initialization, this is still just a declaration and not the definition. You won't generally need the definition, although there are certain cases when you would.

请注意,静态常量变量的内联初始化仅适用于类型为整型的变量。还要注意,无论初始化如何,这仍然只是一个声明而不是定义。您通常不需要定义,尽管在某些情况下需要。

As for the visibility, you can provide a static getter function that would return MAX_SONGS.

至于可见性,您可以提供一个返回 MAX_SONGS 的静态 getter 函数。

public:
static int GetMaxSongs() { return MAX_SONGS; }

回答by James McNellis

const int MAX_SONGS = 30is considered a variable right?

const int MAX_SONGS = 30被认为是一个变量吗?

Yes, MAX_SONGSis a variable, but it is a constantvariable. It can't change.

是的,MAX_SONGS是一个变量,但它是一个常量变量。它不能改变。

It's not so much that global variables are inadvisable, it's that global mutable state is inadvisable, if it can be avoided. There is no mutable state here: MAX_SONGScannot change.

与其说全局变量不可取,不如说全局可变状态是不可取的,如果可以避免的话。这里没有可变状态: MAX_SONGS不能改变。

回答by Lee Scott

You could also use the #definepreprocessor comand.

您也可以使用#define预处理器命令。

in Album.h

在相册.h

#define MAX_SONGS 30

in Album.cpp

在相册.cpp

#include "Album.h"
class Album {
private:
    Song songs[MAX_SONGS];
//...
}

回答by waas1919

To avoid staticusage, use enum:

为避免static使用,请使用enum

class Album {
    private:
        enum { MAX_SONGS = 30 };
        Song songs[MAX_SONGS];

        //...
    }