简体   繁体   English

C ++编译时间错误:数字常量之前的预期标识符

[英]C++ compile time error: expected identifier before numeric constant

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;
}

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 eg in a contructor 在C ++ 11之前,您需要先声明它们,然后在例如构造器中对其进行初始化

class Foo {
    vector<string> name;
    vector<int> val;
 public:
  Foo() : name(5), val(5,0) {}
};

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) {}

由于您的编译器可能还不支持所有C ++ 11(支持相似的语法),因此会出现这些错误,因为您必须在构造函数中初始化类成员:

Attribute() : name(5),val(5,0) {}

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

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