【C++】转换构造函数

在C/C++中,允许不同数据类型之间进行数据类型的转换,有两种转换方式,编译器自动识别转换的称为自动类型转换(隐式类型转换),用户指明如何转换的称为强制类型转换(显示类型转换)。


这两种方法使用于编译器知道如何转换的类型转换。


C++允许用户自定义转换规则,用户可以将其他类型转换为当前数据类型,也可以将当前数据类型转换为其他数据类型。这种自定义的转换规则值能以类的成员函数的形式实现。



将其他类型转化为当前类类型需要借助转换构造函数,转换构造函数只能有一个参数。

以Complex类为例:

#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);是转换构造函数,作用是将double类型的参数real转换为Complex类的对象,并将real作为复数的实部,虚部默认为零。


所以a=3.0等价于a.Complex(3.0);
将复制过程转换为函数调用的过程。

猜你喜欢

转载自blog.csdn.net/zhangxia_/article/details/121534143
今日推荐