C++ 错误:非静态数据成员的无效使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29734072/
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
error: invalid use of non-static data member
提问by user3584564
class Stack
{
private:
int tos;
const int max = 10;
int a[max];
public:
void push(int adddata);
void pop();
void printlist();
};
error: invalid use of non-static data member 'max'
错误:非静态数据成员“max”的无效使用
whats wrong in the code, and please help me with proper correction. Thankyou
代码有什么问题,请帮助我进行适当的更正。谢谢
回答by Titus
It is mandatory that the array size be known during compile time for non-heap allocation (not using new
to allocate memory).
对于非堆分配(不new
用于分配内存),必须在编译时知道数组大小。
If you are using C++11, constexpr
is a good keyword to know, which is specifically designed for this purpose.
如果您使用的是 C++11,这constexpr
是一个很好的关键字,它是专门为此目的而设计的。
constexpr int max = 10;
If you are not having C++11 yet, use static
to make it a compile time constant as others have pointed out.
如果您还没有 C++11,请使用static
使其成为其他人指出的编译时常量。
回答by Vinay Shukla
As the error says, max is a non-static member of Stack; so you can only access it as part of a Stack object. You are trying to access it as if it were a static member, which exists independently of any objects.
正如错误所说,max 是 Stack 的非静态成员;所以你只能作为 Stack 对象的一部分访问它。您试图访问它,就好像它是一个独立于任何对象而存在的静态成员。
Hence you need to make it static.
因此,您需要将其设为静态。
static const int max = 10;
If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.
如果初始化在头文件中,那么包含头文件的每个文件都将具有静态成员的定义。因此,在链接阶段,您将收到链接器错误,因为初始化变量的代码将在多个源文件中定义。
回答by Vlad from Moscow
As the compiler says make the data member static
正如编译器所说,使数据成员静态
static const int max = 10;
回答by Johan Lundberg
You need to make max a compile time constant:
您需要使 max 成为编译时间常数:
static const int max = 10;
回答by Anchellon
The Conceptual mistake that you are making is that you are trying to initialize values for the class in the class definition .This is the reason why constructors exist .Using a parametrized constructor set values of top of stack and its size. When making the stack object pass the size of the stack to be created:
您犯的概念性错误是您试图在类定义中初始化类的值。这就是构造函数存在的原因。使用参数化构造函数设置栈顶值及其大小。当使堆栈对象传递要创建的堆栈的大小时:
class Stack {
private:
int tos;
int a[max];
public:
Stack(int s);
void push(int adddata);
void pop();
void printlist();
};
Stack::Stack(int s) {
tos=-1;
max=s;
}