0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C++で string が「型として認識されない」エラーの原因と解決策

Posted at

発生したエラー

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::vectorvectorとして認識されて、class vector {}と名前衝突してしまうため。

そのため①のstringstd::をつけるのが無難な選択肢となる。

小規模開発なら開発スピードを上げるという判断で②のusing namespace std;を使ってもいい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?