C++ 解决“只能在类中初始化静态常量整数数据成员”编译错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/498433/
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
Resolving "only static const integral data members can be initialized within a class" compilation error
提问by OneShot
The following for creating a Global Object is resulting in compilation errors.
以下创建全局对象会导致编译错误。
#include "stdafx.h"
#include <iostream>
using namespace System;
using namespace std;
#pragma hdrstop
class Tester;
void input();
class Tester
{
static int number = 5;
public:
Tester(){};
~Tester(){};
void setNumber(int newNumber)
{
number = newNumber;
}
int getNumber()
{
return number;
}
}
Tester testerObject;
void main(void)
{
cout << "Welcome!" << endl;
while(1)
{
input();
}
}
void input()
{
int newNumber = 0;
cout << "The current number is " << testerObject.getNumber();
cout << "Change number to: ";
cin >> newNumber;
cout << endl;
testerObject.setNumber(newNumber);
cout << "The number has been changed to " << testerObject.getNumber() << endl;
}
Here are the compile errors:
以下是编译错误:
1>------ Build started: Project: test, Configuration: Debug Win32 ------
1>Compiling...
1>test.cpp
1>.\test.cpp(15) : error C2864: 'Tester::number' : only static const integral data members can be initialized within a class
1>.\test.cpp(33) : error C2146: syntax error : missing ';' before identifier 'testerObject'
1>.\test.cpp(33) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>.\test.cpp(49) : error C2039: 'getNumber' : is not a member of 'System::Int32'
1> c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll : see declaration of 'System::Int32'
1>.\test.cpp(55) : error C2039: 'setNumber' : is not a member of 'System::Int32'
1> c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll : see declaration of 'System::Int32'
1>.\test.cpp(57) : error C2039: 'getNumber' : is not a member of 'System::Int32'
1> c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll : see declaration of 'System::Int32'
1>Build log was saved at "file://c:\Users\Owner\Documents\Visual Studio 2008\Projects\test\test\Debug\BuildLog.htm"
1>test - 6 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
- How do I create a Global Class Object correctly like I've attempted here.
- And how do I fix that "only static const integral data members can be initialized within a class"
- And basically how do I fix the rest of the errors so I can get this to compile?
- 如何像我在这里尝试的那样正确创建全局类对象。
- 以及如何解决“只能在类中初始化静态常量整数数据成员”的问题
- 基本上我该如何修复其余的错误,以便我可以编译它?
I like declaring Global Class Objects at file scope (I like declaring all globals at file scope) because when I have to create separate source files and do "extern" and everything it becomes extremely complicated and never works for me. Although, I do want to figure out how to do that eventually... it seems every tutorial I look at won't compile though and unless it compiles I have no idea how to recreate it!
我喜欢在文件范围内声明全局类对象(我喜欢在文件范围内声明所有全局对象),因为当我必须创建单独的源文件并执行“extern”时,一切都会变得非常复杂,而且对我来说永远不起作用。虽然,我确实想最终弄清楚如何做到这一点......似乎我看到的每个教程都不会编译,除非它编译我不知道如何重新创建它!
If I can just get this to compile...then I can successfully learn how to do this. So if someone could rewrite the above to where it literally copies & pastes into Visual C++ Express 2008 and works I will finally be able to figure out how to recreate it. I'm extremely excited on seeing the fix for this! It is just I can't get Global Objects to work right! Any other information on declaring Global Class Objects...or anything for that matter is welcome!
如果我能让它编译……那么我就可以成功地学习如何做到这一点。因此,如果有人可以将上述内容重写为将其复制并粘贴到 Visual C++ Express 2008 中并有效的地方,我将最终能够弄清楚如何重新创建它。看到此问题的修复,我感到非常兴奋!只是我无法让全局对象正常工作!欢迎任何其他有关声明全局类对象的信息……或任何与此相关的信息!
回答by Michael Burr
Just start addressing the errors one by one. A lot of the errors are just cascaded from the initial errors, so it looks like there are a lot of problems when there's only a couple. Just start from the top:
只需开始一一解决错误。很多错误只是从初始错误级联而来,所以当只有几个错误时,看起来问题很多。只需从顶部开始:
1>.\test.cpp(15) : error C2864: 'Tester::number' : only static const integral data members can be initialized within a class
You can't initialize a member in the class definition unless it's static, const, and one of the integral types. Leave the "= 5
" off of the declaration of number
. Then you'll need to have a definition of Tester::number
outside of the class definition, like so:
您不能在类定义中初始化成员,除非它是静态、常量和整数类型之一。将“ = 5
”从 的声明中去掉number
。然后你需要Tester::number
在类定义之外有一个定义,如下所示:
int Tester::number = 5;
Problem #2:
问题#2:
1>.\test.cpp(33) : error C2146: syntax error : missing ';' before identifier 'testerObject'
Almost exactly what it says (missing semi-colon errors can be a bit inexact in saying where the semicolon should be) - you need a semi-colon after the definition of the Tester
class.
几乎正是它所说的(缺少分号错误在说明分号应该在哪里时可能有点不准确) - 在Tester
类定义之后需要一个分号。
Fix those and your compilation problems go away.
解决这些问题,您的编译问题就会消失。
The key thing is to try and take compiler errors one at a time from the top. If you get more than about 3 of them, you can probably just ignore everything after the 3rd or so because the initial error just cause the compile to into the weeds (and if they are real errors, they'll show up again in the next compile anyway).
关键是尝试从顶部一次一个地处理编译器错误。如果你得到超过 3 个,你可能会在第 3 个左右之后忽略所有内容,因为初始错误只会导致编译成为杂草(如果它们是真正的错误,它们将再次出现在下一个无论如何编译)。
回答by Hosam Aly
- Error C2864: either add a
const
modifier to your integer, or move the initialization outside the class (as inclass Tester { static int number; }; int Tester::number = 5;
). The latter seems more appropriate to your case. - Error C2146: you're missing a semicolon after the declaration of
class Tester { ... }
. It should beclass Tester { ... }
;
- 错误 C2864:
const
向整数添加修饰符,或将初始化移到类之外(如 中所示class Tester { static int number; }; int Tester::number = 5;
)。后者似乎更适合您的情况。 - 错误 C2146:在
class Tester { ... }
. 它应该是class Tester { ... }
;
The other errors are probably caused by the previous error. They should fix themselves automatically when it is fixed.
其他错误可能是由上一个错误引起的。当它被修复时,他们应该自动修复自己。
As a side note, I don't think you really want the static
modifier on your member. It seems more appropriate for an instance field. You still can't initialize it in-place though (this isn't C#), you have to move the initialization to the constructor. For example:
作为旁注,我认为您并不真正想要static
您的成员的修饰符。它似乎更适合实例字段。您仍然无法就地初始化它(这不是 C#),您必须将初始化移动到构造函数。例如:
class Tester {
int number;
static int staticNumber; // just to show you how to use a static field
public:
Tester() : number(5) {}
~Tester() {} // I suggest you remove the destructor unless you need it
int getNumber() { return number; }
void setNumber(int value) { number = value; }
static int getStaticNumber() { return staticNumber; }
static void setStaticNumber(int value) { staticNumber = value; }
};
// initialize static members *outside* the class
int Tester::staticNumber = 5;
回答by jheriko
the answers already here deal with why your code doesn't compile and how to correct that. however i am intrigued by your comments about "extern". it is very easy to use when you know how. you declare in one header the extern'ed variable. and then you initialise it in one file. any other file can refer to the variable by including the header. e.g.
此处已有的答案涉及为什么您的代码无法编译以及如何更正。但是我对你关于“extern”的评论很感兴趣。当您知道如何使用时,它非常容易使用。您在一个标题中声明了 extern'ed 变量。然后你在一个文件中初始化它。任何其他文件都可以通过包含标题来引用该变量。例如
header.h:
标题.h:
// ensure the file is only included once
#ifndef _HEADER_H
#define _HEADER_H
extern int foo;
#endif
// end file header.h
header.cpp
头文件
#include "header.h"
int foo = 1;
// end file header.cpp
main.cpp
主程序
#include "header.h"
#include <stdio.h>
int main(int argc, char** argv)
{
printf("%d", foo);
return 0;
}
// end file main.cpp
Whilst using static class members for global variables helps fit the oo design scheme, its more elaborate than necessary. if you don't have to follow oo strictly, just use extern, its easier and its less code.
虽然对全局变量使用静态类成员有助于适应 oo 设计方案,但它比必要的更复杂。如果您不必严格遵循 oo,只需使用 extern,它更容易且代码更少。
回答by abelenky
According to this: http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/cplr038.htm
根据这个:http: //publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/cplr038.htm
Tester testerObject;
int Tester::number = 5;
I'm not positive, but I think the rest of the errors come from that one problem. Fix that, and see how far it gets you.
我并不乐观,但我认为其余的错误都来自这一问题。解决这个问题,看看它能让你走多远。