発生したエラー
main.cpp:18:5: error: ‘string’ does not name a type; did you mean ‘stdin’?
18 | string getHex(void) {
| ^~~~~~
| stdin
stringが型として認識されていないよって。
原因
#include <string>
でライブラリの読み込みはしていたが、名前空間の指定をしていなかった。
解決策
C++の標準ライブラリは名前衝突が起きないようにstd
という名前空間の中にある。
そのため以下でいずれかの方法でstring
を認識させる。
①名前空間を明示的に記載する(無難な選択肢)
#include <iostream>
#include <string>
std::string getHex(void) { // std::を指定する
return "";
}
int main (void) {
return 0;
}
②using namespace std;
を記載しておく。
#include <iostream>
#include <string>
using namespace std; // これがあるとstd::を省略できる
string getHex(void) {
return "";
}
int main (void) {
return 0;
}
②はstd::
を省略できるが、名前衝突のリスクがある。
例えば以下ではエラーが発生する。
#include <vector>
using namespace std;
class vector {
};
int main (void) {
return 0;
}
なぜならusing namespace std;
を使うと、std::vector
もvector
として認識されて、class vector {}
と名前衝突してしまうため。
そのため①のstring
にstd::
をつけるのが無難な選択肢となる。
小規模開発なら開発スピードを上げるという判断で②のusing namespace std;
を使ってもいい。