【问题标题】:Problems after commenting out "using namespace std;"注释掉“using namespace std;”后的问题
【发布时间】: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 后缀,而不是coutusing std::operator""s
  • @Ryan using namespace std::string_literals; 是更传统的方法。

标签: gcc namespaces c++14 using-directives return-type-deduction


【解决方案1】:

clang++ 给出了一个很好的错误信息:

error: no matching literal operator for call to 'operator""s' with arguments of types 'const char *' and 'unsigned long', and no matching literal operator template
auto main() -> int { std::cout << add("We have C", "++14!"s); }
                                                          ^

您使用字符串文字,更准确地说是operator""s

通过删除using namespace std;,您必须指定定义运算符的命名空间。

显式调用:

int main() {
  std::cout << add("We have C", std::operator""s("++14!", 5));
  // Note the length of the raw character array literal is required
}

或使用using 声明:

int main() {
  using std::operator""s;
  std::cout << add("We have C", "++14!"s);
}

【讨论】:

  • 首选using namespace std::string_literals
猜你喜欢
  • 1970-01-01
  • 2011-10-14
  • 2011-09-22
  • 2016-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多