在 C++ 中,std::string 和 string 实际上是同一个类型,只是它们的命名空间(namespace)不同。具体来说:(我说为啥在写代码的时候都有个using namespace std;语句我还以为是闹着玩.)
-
std::string明确指定了string类型位于std命名空间中。 -
string是std::string的简写,但要使用它,你需要在代码中声明using namespace std;或者using std::string;。
1. 使用 std::string
这是最安全和最明确的方式,可以避免命名冲突。推荐在大型项目或库中使用这种方式。
#include <iostream>
#include <string>
int main() {
std::string s = "Hello, World!";
std::cout << s << std::endl;
return 0;
}
2. 使用 using namespace std;
这种方式会将 std 命名空间中的所有名称都引入到当前作用域中。虽然代码看起来更简洁,但可能会导致命名冲突,特别是在大型项目中。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello, World!";
cout << s << endl;
return 0;
}
命名冲突示例
假设你有一个自定义的 string 类型,同时又使用了 using namespace std;,这将导致命名冲突:
#include <iostream>
#include <string>
using namespace std;
class string {
public:
string(const char* s) {
// 自定义的字符串类
}
};
int main() {
string s = "Hello, World!"; // 编译错误:ambiguous
return 0;
}
在这个示例中,编译器不知道 string 是指 std::string 还是自定义的 string 类,从而导致编译错误。
总结
-
推荐使用
std::string:明确且安全,避免命名冲突。 -
谨慎使用
using namespace std;:虽然代码更简洁,但可能导致命名冲突,特别是在大型项目中。 -
使用
using std::string;:只引入需要的类型,避免命名冲突。
后面我又看见既然string是用std::string来的,那么有没有str::int函数?AI告诉我不存在str::int,因为C++中直接有int类型.
696

被折叠的 条评论
为什么被折叠?



