C++ 编译时错误:数字常量前的预期标识符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11490988/
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
C++ compile time error: expected identifier before numeric constant
提问by user1484717
I have read other similar posts but I just don't understand what I've done wrong. I think my declaration of the vectors is correct. I even tried to declare without size but even that isn't working.What is wrong?? My code is:
我读过其他类似的帖子,但我只是不明白我做错了什么。我认为我对向量的声明是正确的。我什至试图在没有尺寸的情况下声明,但即使这样也不起作用。有什么问题??我的代码是:
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <cmath>
using namespace std;
vector<string> v2(5, "null");
vector< vector<string> > v2d2(20,v2);
class Attribute //attribute and entropy calculation
{
vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);
public:
Attribute(){}
int total,T,F;
};
int main()
{
Attribute attributes;
return 0;
}
回答by juanchopanza
You cannot do this:
你不可以做这个:
vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);
in a class outside of a method.
在方法之外的类中。
You can initialize the data members at the point of declaration, but not with ()
brackets:
您可以在声明点初始化数据成员,但不能使用()
括号:
class Foo {
vector<string> name = vector<string>(5);
vector<int> val{vector<int>(5,0)};
};
Before C++11, you need to declare them first, then initialize them e.g in a contructor
在 C++11 之前,您需要先声明它们,然后在例如构造函数中初始化它们
class Foo {
vector<string> name;
vector<int> val;
public:
Foo() : name(5), val(5,0) {}
};
回答by Johannes Schaub - litb
Initializations with (...)
in the class body is not allowed. Use {..}
or = ...
. Unfortunately since the respective constructor is explicit
and vector
has an initializer list constructor, you need a functional cast to call the wanted constructor
(...)
不允许在类主体中进行初始化。使用{..}
或= ...
。不幸的是,由于各自的构造函数是explicit
并且vector
有一个初始化列表构造函数,你需要一个函数式转换来调用想要的构造函数
vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);
As an alternative you can use constructor initializer lists
作为替代方案,您可以使用构造函数初始值设定项列表
Attribute():name(5), val(5, 0) {}
回答by slartibartfast
Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:
由于您的编译器可能还不支持所有支持类似语法的 C++11,因此您会收到这些错误,因为您必须在构造函数中初始化您的类成员:
Attribute() : name(5),val(5,0) {}