C++类型转换构造函数

为何要有这玩意

传说中,是为了实现类型的自动转换ios

定义

  • 只有一个参数,类型任意this

  • 意思是,把一个任意类型的变量,自动转换成我这个类型spa

#include <iostream>
#include <stdio.h>

using namespace std;

class Complex {
public:
    int real;
    int imaginary;
    
    Complex(int real) {
        this->real = real;
        this->imaginary = 0;
        cout << "Complex(int real)" << endl;
    }
    
    ~Complex() {
        cout << "~Complex() - " << real << endl;
    }
    
};

int main() {
    Complex c = 12; // 至关于下面那句
//    Complex c = Complex(12); // c变量是以Complex(12)的方式初始化
    c = 10; // 至关于下面那句
    // 建立一个临时对象,让后将临时对象的值拷贝给c,拷贝完成后临时对象销毁
//    c = Complex(10); 
    return 0;
}
相关文章
相关标签/搜索