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;
}
相關文章
相關標籤/搜索