为什么调用了不合适的重载函数?
Why is the unsuitable overloaded function is called?
为什么下面的代码总是打印"type is double"? (我在 Whosebug 上看到过这段代码)
#include <iostream>
void show_type(...) {
std::cout << "type is not double\n";
}
void show_type(double value) {
std::cout << "type is double\n";
}
int main() {
int x = 10;
double y = 10.3;
show_type(x);
show_type(10);
show_type(10.3);
show_type(y);
return 0;
}
http://en.cppreference.com/w/cpp/language/overload_resolution 说:
A standard conversion sequence is always better than a user-defined conversion sequence or an ellipsis conversion sequence.
void show_type(double value) {
std::cout << "type is double\n";
}
如果您在行上方发表评论,则输出将为
type is not double
type is not double
type is not double
type is not double
这意味着编译总是优先选择 void show_type(double value)
而不是 void show_type(...)
。
在你的情况下,如果你想调用方法 void show_type(...) 在调用此方法时传递两个或更多参数 show_type(firstParameter,secondParameter)
#include <iostream>
void show_type(...) {
std::cout << "type is not double\n";
}
void show_type(double value) {
std::cout << "type is double\n";
}
int main() {
int x = 10;
double y = 10.3;
show_type(x);
show_type(10);
show_type(10.3);
show_type(y);
show_type(4.0,5); //will called this method show-type(...)
return 0;
}
现在上面一行的输出将是
type is double
type is double
type is double
type is double
type is not double //notice the output here
more info on var-args
为什么下面的代码总是打印"type is double"? (我在 Whosebug 上看到过这段代码)
#include <iostream>
void show_type(...) {
std::cout << "type is not double\n";
}
void show_type(double value) {
std::cout << "type is double\n";
}
int main() {
int x = 10;
double y = 10.3;
show_type(x);
show_type(10);
show_type(10.3);
show_type(y);
return 0;
}
http://en.cppreference.com/w/cpp/language/overload_resolution 说:
A standard conversion sequence is always better than a user-defined conversion sequence or an ellipsis conversion sequence.
void show_type(double value) {
std::cout << "type is double\n";
}
如果您在行上方发表评论,则输出将为
type is not double type is not double type is not double type is not double
这意味着编译总是优先选择 void show_type(double value)
而不是 void show_type(...)
。
在你的情况下,如果你想调用方法 void show_type(...) 在调用此方法时传递两个或更多参数 show_type(firstParameter,secondParameter)
#include <iostream>
void show_type(...) {
std::cout << "type is not double\n";
}
void show_type(double value) {
std::cout << "type is double\n";
}
int main() {
int x = 10;
double y = 10.3;
show_type(x);
show_type(10);
show_type(10.3);
show_type(y);
show_type(4.0,5); //will called this method show-type(...)
return 0;
}
现在上面一行的输出将是
type is double type is double type is double type is double type is not double //notice the output here
more info on var-args