[英]c++ error: why this error shows " expected type specifier in vector "
我包含了向量,但是當我在 class 中聲明一個向量時,它顯示一個錯誤(預期的類型說明符)我的代碼是否正確?
#include <vector>
#include <string>
class Ecole {
vector<string> arr(10);
};
正如已經提到的其他答案,您將需要在向量和字符串的前面編寫命名空間 std。
另外我會假設您必須像這樣初始化變量:
std::vector<std::string> arr = std::vector<std::string>(10);
因為您不能直接在 class 內部使用(10)
來初始化它。 (方法外)
vector
和string
在命名空間std
中聲明,所以使用命名空間來引用它們。
#include <vector>
#include <string>
class Ecole {
std::vector<std::string> arr(10);
};
如果你想每次都擺脫 using std
,你可以寫using namespace std;
class 聲明之前;
#include <vector>
#include <string>
using namespace std;
class Ecole {
vector<string> arr(10);
};
但這是個壞主意,請參閱鏈接Why is "using namespace std;" 被認為是不好的做法?
另一個問題是你試圖初始化arr(10)
向量而不直接引用 class 中的任何變量,你必須在 class 中聲明和初始化。
class Ecole {
std::vector<std::string> arr = std::vector<std::string>(10);
};
如果你想在構造函數中聲明然后初始化。
#include <vector>
#include <string>
class Ecole {
std::vector<std::string> arr;
Ecole(){
this->arr = std::vector<std::string>(10);
}
};
如果您只想在沒有 class 的情況下使用矢量,您可以直接在主 function 中使用。
#include <vector>
#include <string>
int main() {
std::vector<std::string> arr(10);
// start playing here
return 0;
}
我敢打賭,如果您將<string>
替換為<std::string>
並將<vector>
替換為<std::vector>
問題是string
包含在std
命名空間中,因此必須相應解決。
使其工作的另一種方法是添加
using namespace std;
...在class
聲明之上,盡管據說這是不好的做法,如下所述: https://www.geeksforgeeks.org/using-namespace-std-considered-bad-practice/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.