提问人:q-l-p 提问时间:12/6/2016 最后编辑:q-l-p 更新时间:5/3/2021 访问量:898
注释掉“using namespace std”后出现的问题;”
Problems after commenting out "using namespace std;"
问:
我是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;
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)) ===|
问题:
- 是什么原因导致了第二个程序中的错误?
- 在这种情况下如何避免?
using namespace std
答:
3赞
user4268862
12/7/2016
#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); }
^
您可以使用字符串文字,更准确地说是运算符“”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);
}
评论
1赞
Nicol Bolas
11/27/2017
喜欢。using namespace std::string_literals
评论
s
cout
using std::operator""s
using namespace std::string_literals;