C++ 中的转换构造函数是什么?


本节将介绍 C++ 中的转换构造函数或构造转换的函数。构造函数是一类特殊类型的函数。它有一些惟一属性,例如,它的名称与类名称相同,它不会返回任何值,等等。构造函数用于构建类对象。有时,构造函数可能会使用一些参数,而有时则不会。

当构造函数仅使用一个参数时,此类构造函数就成为转换构造函数。此类构造函数允许自动转换为正在构造的类。

示例

#include<iostream>
using namespace std;
class my_class{
   private:
      int my_var;
   public:
      my_class(int x){
         this->my_var = x; //set the value of my_var using
         parameterized constructor
      }
      void display(){
      cout << "The value of my_var is: " << my_var <<endl;
   }
};
int main() {
   my_class my_obj(10);
   my_obj.display();
   my_obj = 50; //here the conversion constructor is called
   my_obj.display();
}

输出

The value of my_var is: 10
The value of my_var is: 50

更新于: 2019 年 7 月 30 日

151 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.