BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #102644同步于 2023/5/4
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

这个函数重载,为啥编译报错

xiaobing307
2023/5/4镜像同步5 回复
#include <iostream> #include <memory> #include <string> using namespace std; std::shared_ptr<int> foo(int a, const std::string& b, const std::string& c) { return make_shared<int>(1); } std::shared_ptr<int> foo(const std::string& a, const std::string& b, bool c) { return make_shared<int>(2); } int main() { auto p = foo(0, "1,2", "2,3"); cout << *p << endl; return 0; } ~/c++ $ g++ hello_world.cpp hello_world.cpp: In function ‘int main()’: hello_world.cpp:17:33: error: call of overloaded ‘foo(int, const char [4], const char [4])’ is ambiguous 17 | auto p = foo(0, "1,2", "2,3"); | ^ hello_world.cpp:7:22: note: candidate: ‘std::shared_ptr<int> foo(int, const string&, const string&)’ 7 | std::shared_ptr<int> foo(int a, const std::string& b, const std::string& c) | ^~~ hello_world.cpp:11:22: note: candidate: ‘std::shared_ptr<int> foo(const string&, const string&, bool)’ 11 | std::shared_ptr<int> foo(const std::string& a, const std::string& b, bool c) { | ^~~
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
Zelda机器人#1 · 2023/5/4
报错跟重载没关系,是因为你传了rvalue给lvalue reference.
TCZY机器人#2 · 2023/5/4
也不是吧,他是const引用,可以传右值 【 在 Zelda 的大作中提到: 】 : 报错跟重载没关系,是因为你传了rvalue给lvalue reference. : --
YiYeShu机器人#3 · 2023/5/4
```c++ // c++17 这个代码说明一切 void foobar() { const std::string& val1{1}; bool val2 = "hello world"; } ``` 【 在 xiaobing307 的大作中提到: 】 : [code=c] : #include <iostream> : #include <memory> : ...................
xiaobing307机器人#4 · 2023/5/4
好像是不一样的。 foo(0, "1,2", "2,3"); 上面这个函数调用编译器会认为0是一个指针,const char*,编译能过,如果改成1,就匹配不上了,编译不通过。 string s{1}; 上面这个能通过编译,是因为构造参数是 std::initializer_list<char>,会把1认为是char的ascii码。 比如 string s{65}; cout << s << endl; 会输出‘A’,因为65是A的ascii码。 #include <iostream> #include <memory> #include <string> using namespace std; std::shared_ptr<int> foo(const std::string& a, const std::string& b, bool c) { return make_shared<int>(2); } int main() { foo(0, "1", "2"); foo(1, "1", "2"); return 0; } ~/c++ $ g++ -g hello_world.cpp hello_world.cpp: In function ‘int main()’: hello_world.cpp:14:9: error: invalid initialization of reference of type ‘const string&’ {aka ‘const std::__cxx11::basic_string<char>&’} from expression of type ‘int’ 14 | foo(1, "1", "2"); | ^ hello_world.cpp:7:45: note: in passing argument 1 of ‘std::shared_ptr<int> foo(const string&, const string&, bool)’ 7 | std::shared_ptr<int> foo(const std::string& a, const std::string& b, bool c) { | ~~~~~~~~~~~~~~~~~~~^ 【 在 YiYeShu 的大作中提到: 】 : [md] : ```c++ : // c++17 这个代码说明一切 : ...................
YiYeShu机器人#5 · 2023/5/4
好的,大概就是因为,你传的参数类型,可以隐式转换成函数里的类型 【 在 xiaobing307 的大作中提到: 】 : 好像是不一样的。 : foo(0, "1,2", "2,3"); : 上面这个函数调用编译器会认为0是一个指针,const char*,编译能过,如果改成1,就匹配不上了,编译不通过。 : ...................