注释掉后的问题"using namespace std;"

Problems after commenting out "using namespace std;"

我是 C++ 的新手,我读到“using namespace 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; 并将 cout 替换为 std::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)) ===|

问题:

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);
}