[C++] Conversion constructor

In C/C++, data type conversion between different data types is allowed. There are two conversion methods. The compiler automatically recognizes the conversion called automatic type conversion (implicit type conversion), and the user specifies how to convert is called coercion. Type conversion (display type conversion).


These two methods are used for type conversions where the compiler knows how to convert.


C++ allows users to customize conversion rules, and users can convert other types to the current data type, and can also convert the current data type to other data types. This custom conversion rule value can be implemented as a member function of the class.



Converting other types to the current class type requires the help of a conversion constructor, which can only have one parameter.

Take the Complex class as an example:

#include<iostream>
using namespace std;
class Complex{
    
    
    public:
    Complex();
    Complex(double);
    Complex(double,double);
    friend Complex operator+(Complex&,Complex&);
    friend ostream& operator<<(ostream&,Complex&);
    friend istream& operator>>(istream&,Complex&);
    private:
    double real,imag;
};
	    Complex::Complex(){
    
    
        real=0.0;
        imag=0.0;
    }
    Complex::Complex(double r){
    
    
        real=r;
    }
    Complex::Complex(double r,double i){
    
    
        real=r;
        imag=i;
    }

Complex operator+(Complex& c1,Complex& c2){
    
    
    Complex c;
    c.imag=c1.imag+c2.imag;
    c.real=c1.real+c2.real;
    return c;
}

ostream& operator<<(ostream &output,Complex &c){
    
    
    output<<"("<<c.real<<"+"<<c.imag<<")"<<endl;
    return output;
}

istream& operator>>(istream &input,Complex &c){
    
    
    cout<<"input real and imaginary part of Complex number:";
    input>>c.real>>c.imag;
    return input;
}
int main()
{
    
    
    Complex a(1.0,2.0);
    cout<<a<<endl;
    a=3.0;//调用转换构造函数
    cout<<a<<endl;
    return 0;
}

Complex(double r);It is a conversion constructor, which converts the parameter real of double type into an object of the Complex class, and uses real as the real part of the complex number, and the imaginary part defaults to zero.


So a=3.0 is equivalent to a.Complex(3.0);
converting the copy process into a function call process.

Guess you like

Origin blog.csdn.net/zhangxia_/article/details/121534143