C++ 转换构造函数、类型转换函数

本文介绍了C++中的转换构造函数和类型转换函数,转换构造函数用于将其他类型转换为自定义对象,例如double到Complex,而类型转换函数则用于将自定义对象转换回基本类型,如Complex到double。这两种函数在运算符重载中起到关键作用,可以实现如Complex+double=Complex这样的操作。文章还给出了示例代码来演示它们的用法。
摘要由CSDN通过智能技术生成

C++转换构造函数和类型转换函数_梵希栀子的博客-CSDN博客_c++转换构造函数

转换构造函数:

        1、作用:其他类型转换(普通数据类型或者其他)——> 自定义对象

        2、书写格式:Complex (double r) { }   //要求形参只能有一个参数

        3、注意点:转换构造函数配合使用运算符重载函数实现操作数交换律,要求是运算符重载函数是友元函数。

类型转换函数:

        1、作用:自定义对象 ——> 普通类型

        2、书写格式:operator double() { return real; }  //要求函数名称为要转换的类型且函数无形参

        3、注意点:与运算符重载具有二义性,使用过程中需要注意。

比如说,转换构造函数可以把double类型隐式转换为Complex对象,实现Complex +double=Complex 的运算 ;

而类型转换函数是相反的,把Complex对象隐式转换成double对象,实现Complex +double=double。

1.转换构造函数

#include<iostream>
using namespace std;

class Complex {
public:
	Complex (double r) {    // 转换构造函数
		real = r;  
		imag = 0;
	}
 
	Complex() { 
		real = 0;
		imag = 0; 
	}

	Complex(double r, double m) {
		real = r;
		imag = m;
	}

	double getReal(){
		return real;
	}
	double getImag(){
		return imag;
	}
	void display(){
		std::cout << real << " + " << imag << "i\n";
	}
	friend Complex operator+(Complex c1, Complex c2); // 友元函数实现运算符重载
	friend std::ostream& operator<<(std::ostream& output, Complex& c);
private:
	double real;
	double imag;
};
 
Complex operator+(Complex c1, Complex c2){	
	return Complex(c1.real+c2.real, c1.imag+c2.imag);
}

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

int main(){
	Complex c1(3.6, 2);
	c1.display();
	std::cout << "real: " << c1.getReal() << ", imag: " << c1.getImag() << "\n";

	double d2 = 2.1234;
	Complex c2 = c1 + d2;    // 重载+
	c2.display();
	std::cout << c2 << "\n"; // 重载<<

	c2 = d2 + c1;
	c2.display();
}
 

2.类型转换函数

#include<iostream>
using namespace std;

class Complex {
public:
	Complex() { 
		real = 0;
		imag = 0; 
	}

	Complex(double r, double m) {
		real = r;
		imag = m;
	}

	// 类型转换函数   类似于运算符重载的写法,1、要求函数名称为要转换的类型 2、函数无形参 
	operator double(){  
		return real;
	}

	double getReal(){
		return real;
	}
	double getImag(){
		return imag;
	}
	void display(){
		std::cout << real << " + " << imag << "i\n";
	}

private:
	double real;
	double imag;
};

int main(){
	Complex c1(3.6, 2);
	double d1 = 2.1234;
	double d2 = c1 + d1;
	std::cout << "d2: " << d2 << "\n";
	double d3 = d1 + c1;
	std::cout << "d3: " << d3 << "\n";
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值