【发布时间】:2017-04-20 17:43:45
【问题描述】:
我是 C++ 新手,我读过“使用命名空间 std;”被认为是不好的做法。我使用以下代码来测试我的编译器是否符合 c++14:
#include <iostream>
#include <string>
using namespace std;
auto add([](auto a, auto b){ return a+b ;});
auto main() -> int {cout << add("We have C","++14!"s);}
没有错误。然后我开始玩弄代码——就像你做的那样……当你学习新东西的时候。所以我注释掉了using namespace std; 并用std::cout 替换了cout。现在代码看起来像这样:
#include <iostream>
#include <string>
//using namespace std;
auto add([](auto a, auto b){ return a+b ;});
auto main() -> int {std::cout << add("We have C","++14!"s);}
构建消息:
||=== Build: Release in c++14-64 (compiler: GNU GCC Compiler) ===|
C:\CBProjects\c++14-64\c++14-64-test.cpp||In function 'int main()':|
C:\CBProjects\c++14-64\c++14-64-test.cpp|5|error: unable to find string literal operator 'operator""s' with 'const char [6]', 'long long unsigned int' arguments|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
问题:
- 第二个程序出错的原因是什么?
- 在这种情况下如何避免
using namespace std?
【问题讨论】:
-
这是字符串文字上的
s后缀,而不是cout。using std::operator""s -
@Ryan
using namespace std::string_literals;是更传统的方法。
标签: gcc namespaces c++14 using-directives return-type-deduction