[英]C++ compile time error: expected identifier before numeric constant
我讀過其他類似的文章,但我只是不明白自己做錯了什么。 我認為我對向量的聲明是正確的。 我什至試圖聲明沒有大小,但那還是行不通。怎么了? 我的代碼是:
#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);
在方法之外的類中。
您可以在聲明時初始化數據成員,但不能使用()
括號進行初始化:
class Foo {
vector<string> name = vector<string>(5);
vector<int> val{vector<int>(5,0)};
};
在C ++ 11之前,您需要先聲明它們,然后在例如構造器中對其進行初始化
class Foo {
vector<string> name;
vector<int> val;
public:
Foo() : name(5), val(5,0) {}
};
不允許在類主體中使用(...)
進行初始化。 使用{..}
或= ...
不幸的是,由於相應的構造函數是explicit
並且vector
具有初始化列表構造函數,因此您需要進行函數轉換以調用所需的構造函數
vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);
或者,您可以使用構造函數初始化器列表
Attribute():name(5), val(5, 0) {}
由於您的編譯器可能還不支持所有C ++ 11(支持相似的語法),因此會出現這些錯誤,因為您必須在構造函數中初始化類成員:
Attribute() : name(5),val(5,0) {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.