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

2021-12-21 00:00:00 g++ vector c++

我读过其他类似的帖子,但我只是不明白我做错了什么.我认为我对向量的声明是正确的.我什至试图声明没有尺寸,但即使这样也不起作用.有什么问题??我的代码是:

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

推荐答案

你不能这样做:

vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);

在方法之外的类中.

你可以在声明点初始化数据成员,但不能用()括号:

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

在 C++11 之前,您需要先声明它们,然后初始化它们,例如在构造函数中

Before C++11, you need to declare them first, then initialize them e.g in a contructor

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

相关文章