Yvo*_*nne 2 c++ string namespaces header using-directives
我在C++中包含头文件时遇到问题.据我所知,放入using namespace std标题并不是一个好的设计,但是当我尝试删除它时出现了一些错误.这是头文件中的代码:
#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;
};
Run Code Online (Sandbox Code Playgroud)
我确实包含了<string>.但是,如果我不使用namespace 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;
};
Run Code Online (Sandbox Code Playgroud)
正如经验法则:每当(甚至在.cpp文件中)使用标准库中的任何数据类型或算法时,只需在其前面加上std::.它足够短,可以输入,它将为您节省痛苦的世界.
高级用户在函数范围使用声明时有一些原因,例如,当您想要swap从标准库重载函数(例如)以使用您自己的数据类型(在他们自己的命名空间内)时.请参阅此问答,了解其工作原理.