在我看来,当有人放入一个恰好与根级命名空间同名的新命名空间并且神秘地改变了许多程序的含义时,使用未锚定的命名空间只会引发麻烦.那么,为什么人们总是说std::
而不是::std::
.他们真的应该说"我想用任何std
方便的东西,而不是根本的东西."?
这是我的意思的一个例子:
在fred/Foo.h中:
#include <string>
namespace fred {
class Foo {
public:
void aPublicMember(const std::string &s);
};
} // end namespace fred
Run Code Online (Sandbox Code Playgroud)
在fred/Bar.h中:
namespace fred {
namespace std { // A standard fred component
class string { // Something rather unlike the ::std::string
// ...
};
} // namespace std
class Bar {
public:
void aPublicMember(std::string &s);
};
} // namespace fred
Run Code Online (Sandbox Code Playgroud)
在oops.cpp中:
#include <string>
#include "fred/Bar.h"
#include "fred/Foo.h" // Oops, the meaning of …
Run Code Online (Sandbox Code Playgroud) 我有一个std::string
包含二进制数据的对象,我需要将其写入文件.可能ofstream f("name"); f << s;
有问题吗?我需要完全按照原来的方式读回数据.
我当然可以使用fwrite(s.c_str(), s.size(), 1, filep)
,这两种方法都有任何优点/缺点吗?