繁体   English   中英

Static class 的 const 数据成员作为相同 class 的成员数组的大小?

[英]Static const data member of a class as a size of a member array of the same class?

我正在通过固定大小的 arrays 制作列表 class。我想在 class 中声明ARRAY_SIZE作为 static const 数据成员因此我的 class 是自包含的,我也可以将它用作数组的大小在 array18112195188 声明中但是我收到错误消息“数组绑定不是']'之前的 integer 常量”

我知道我可以将该语句用作全局变量,如const int LIST_SIZE = 5;

但我想让它成为 class 的 static 常量数据成员。

class List
{
public :
    List() ; //createList
    void insert(int x , int listIndex) ;
    void removeIndex(int listIndex) ; //index based remove
    void removeValue(int listValue) ; //value based remove
    void removeAll() ;
    int find(int x) ;
    void copy(List *listToCopy) ;
    void update(int x , int index) ;
    bool isEmpty() ;
    bool isFull() ;
    int get(int index) ;
    int sizeOfList() ;
    void printList() ;

private :
    //int translate ( int position ) ;
    static const int LIST_SIZE ;
    int items[LIST_SIZE] ;
    int current ;
    int size ;
} ;
//********** END OF DECLARATION OF LIST CLASS **********//

//Definition of static data member of LIST
const int List::LIST_SIZE = 5 ;

错误消息是不言自明的。 在 C++ 语言中,普通原始数组或std::array的大小必须是(编译时或constexpr常量 修饰符const只是一个 promise ,您正在向编译器制作该值永远不会改变的值,但这不足以使变量在只有真正的常量可以使用的地方可用。

constexpr中的魔法词:

    ...
    static const constexpr int LIST_SIZE = 5;
    int items[LIST_SIZE];
    int current;
    int size;
};
//********** END OF DECLARATION OF LIST CLASS **********//

//Definition of static data member of LIST
const int List::LIST_SIZE;

暂无
暂无

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

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