C++中单参数构造函数若不声明为explict,在合适的场合可以产生隐式转换:由成员变量类型转换为类类型。

  下面的代码展示如何实现反向的转换: 

 1 void changeFontSize(FontHandle f, int newsize);
 2 class Font{
 3 public:
 4     operator FontHandle() const   //隐式转换函数
 5     {
 6         return f;
 7     }
 8 private:
 9     FontHandle f;
10 };
11 
12 Font f;
13 int newsize;
14 changeFontSize(f, newsize);      //将Font隐式转换成FontHandle
15 

 

   另外,两个或更多参数的non-explicit构造函数,如果所有形参都提供了默认实参,那么在需要一个类类型对象的表达式位置,提供一个first形参类型的对象,编译器也执行隐式转换,转换得到一个类对象。

  如,构造函数Rational(int num1 = 0,  int num2 = 1); Rational类中重载了operator*。表达式result = oneHalf * 2; 2发生隐式转换为Rational对象。result 和 onehalf为Rational对象。 

相关文章:

  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
  • 2021-10-19
  • 2021-07-19
  • 2022-12-23
  • 2022-02-28
  • 2022-12-23
猜你喜欢
  • 2021-10-24
  • 2022-12-23
  • 2022-12-23
  • 2021-06-15
  • 2022-12-23
  • 2022-12-23
  • 2021-06-07
相关资源
相似解决方案