gpt4 book ai didi

c++ - 为什么删除 using namespace std 会导致我的项目出错?

转载 作者:太空狗 更新时间:2023-10-29 23:52:14 29 4
gpt4 key购买 nike

我在 C++ 中包含头文件时遇到问题。据我所知,把 using namespace std 放在一起不是一个好的设计。在 header 内,但是当我尝试删除它时出现了一些错误。这是我在头文件中的代码:

#include <iostream>
#include <string>

//using namespace std;
class Messages
{
public:
Messages(string sender, string recipient,int time);
void append();
string to_string();


private:
int time;
string sender;
string recipient;
string text;

};

我确实包括了 <string> .但是,如果我不使用命名空间 std,我的所有字符串都会显示错误。我不想添加 using namespace std在头文件中,因为它是一个糟糕的设计。那么我该如何解决呢?

提前致谢。

最佳答案

到处写std::string

#include <iostream>
#include <string>

//using namespace std;
class Messages
{
public:
Messages(std::string sender, std::string recipient,int time);
void append();
std::string to_string();


private:
int time;
std::string sender;
std::string recipient;
std::string text;

};

作为经验法则:无论何时(即使在 .cpp 文件中)您使用标准库中的任何数据类型或算法,只需在其前面加上 std:: 前缀。它足够简短,可以打字,它将为您省去一个痛苦的世界。

高级用户在函数范围内使用 using 声明有一些原因,例如当您想重载标准库中的函数(例如 swap)以使用您自己的数据类型(在它们自己的命名空间内)时。参见例如this Q&A关于它是如何工作的。

关于c++ - 为什么删除 using namespace std 会导致我的项目出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16686863/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com