隐式转换 [英] implicit conversion

查看:113
本文介绍了隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下示例中,作者对隐式转换提出了几个意见。你能解释这些意见的更多细节,这对我不是很清楚。感谢。

In the following example, the author made several comments on the implicit conversion. Can you explain more detail on these comments, which are not very clear to me. Thanks.

class String{
  explicit String(int n);
  String(const char *p);
}
String  s1= ‘a’;     //error:  no implicit char->String conversion
void f(String);
String g( )
{
   f(10);           // error: no implicit int->String conversion
   return 10;   //  error:  no implicit int-> String conversion
}


推荐答案

由于没有转换或选择的转换标记为 explicit ,编译器将给您一个错误的情况。代码可能会更清楚与实际工作的情况:

The author is documenting cases in which the compiler will give you an error because either there is no conversion, or the conversion selected is marked explicit. The code might be clearer with a case that would actually work:

class String{
  explicit String(int n);
  String(const char *p);
};
String  s1= ‘a’;     //error:  no implicit char->String conversion
                     // There is a combo implicit/explicit one...
                     // char (implicit) -> int (explicit) -> String

void f(String);

String g( )
{
   f(10);       //  error: no implicit int->String conversion
                //  (the String(int n) constructor is marked explicit).

   f("fred");   //  not an error: uses the String(const char *) constructor
                //  for an implicit conversion.

   f(String(10)); // not an error, explicitly calls the String(int n)
                  // constructor.

   return 10;   //  error:  no implicit int-> String conversion
}

这篇关于隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆