重载解析,cpp
我知道,如果有多个具有相同名称和相同数量参数的函数,编译器会尝试找到最佳匹配(到目前为止我是对的吗?)
我不明白的是类型提升和类型转换之间的区别。
假设我有这个函数 decleration: void foo (double x)
,然后在 main: 内部:
int x = 5;
foo(x);
这被认为是转换还是升级?
I understand that if there are several function with the same name and same number of parameters the compiler is trying to find the best match (am I right so far?)
What I don't understand is the difference between type promotion and type conversion.
Say I have this function decleration: void foo (double x)
and then inside main:
int x = 5;
foo(x);
Is that considered conversion or promotion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
类型提升是类型转换的特例。
http://en.wikipedia.org/wiki/Type_conversion#Type_promotion
Type promotion is special case of type conversion.
http://en.wikipedia.org/wiki/Type_conversion#Type_promotion
您的示例不起作用,
您需要有 2 个重载方法
1.) void foo(double x){method code} 和
2.) void foo(int x){method code}
然后当您运行代码
int x = 5 ;
foo(5)
编译器或运行时环境根据您传入的输入类型知道要调用哪个方法。
如果我想将 int 转换为 double 则不同。我不确定您使用的是什么语言,但在 Java 中,您将使用类型转换进行转换,
这就是类型转换,会将 double 转换为 int。如果有小数部分,就会丢失。
双 d = 5;
int i = (int)d;
我想这就是你要问的。如果不是,请澄清一下
Your example wont work
you would need to have 2 methods for overloading
1.) void foo(double x){method code} and
2.) void foo(int x){method code}
Then when you run the code
int x = 5;
foo(5)
The compiler or run time environment knows which method to call based on the input type you passed in.
If I want to convert an int into a double that is different. I am not sure what language you are using but in Java you would do the conversion using type casting
this is type casting and will convert a double to an int. You will loose the decimal part if there is one.
double d = 5;
int i = (int)d;
I think this is what you are asking. If not please clarify a little