c++ - 错误 : invalid use of non-static data member

标签 c++ arrays compiler-errors

class Stack
{               
private:

    int tos;
    const int max = 10;    
    int a[max];
public:

    void push(int adddata);
    void pop();
    void printlist();
};

错误:无效使用非静态数据成员'max'

代码有什么问题,请帮我更正。 谢谢你

最佳答案

对于非堆分配(不使用 new 分配内存),必须在编译时知道数组大小。

如果您使用的是 C++11,constexpr 是一个很好的关键字,它是专门为此目的而设计的。 [编辑:正如@bornfree 在评论中指出的那样,它仍然需要是静态的]

static constexpr int max = 10;

因此,正如其他人指出的那样,使用 static 使其成为编译时间常量。

关于c++ - 错误 : invalid use of non-static data member,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29734072/

相关文章:

Android NDK pthread_create 显示 “too many arguments, expected 1”

c++ - Vulkan 未能清除深度

arrays - 根据原始索引排序的排序算法

arrays - 如何以蜗牛模式单次循环遍历二维数组?

java - 尝试使用 Collections.sort 对我的数组进行排序,但没有成功

c++ - 分配抽象类类型错误的对象

c++ - 二进制搜索中 mid=(beg+end)/2 和 mid=beg+(end-beg)/2 有什么区别?

c - 如何在C编程中使用多个动态分配?

Android 源代码在 ubuntu 12.04 中构建

c++ - 尝试使用模板扩展类时出现链接错误(LINK 2019)