5.3 类型转换

文章介绍了C++中系统预定义类型与自定义类类型之间的转换,包括隐式转换和显式转换,以及如何通过构造函数和友元运算符进行转换和运算。特别强调了类类型转换为系统预定义类型只能使用成员函数且无参数但有返回值的情况。
摘要由CSDN通过智能技术生成

5.3.1 系统预定义类型之间的转换

隐式转换

显式转换

int(3.5)

5.3.2 类类型与系统预定义类型之间的转换

1)系统预定义类型 - > 类类型

#include "iostream"
using namespace std;
class Complex {
private:
	double real;
	double imag;
public:
	Complex(double r, double i) :real(r), imag(i) {}	//构造函数

	Complex(double r) {
		//转换构造函数,将  系统预定义类型 转换为  类
		//使用时,可以作为构造函数来使用,也可以yongyu无法运算时的类型转换
		real = r;
		imag = 0;
	}

	friend Complex operator+(const Complex& c1, const Complex& c2) {	//友元符号转换
		return Complex(c1.real + c2.real, c1.imag + c2.imag);
	}

	void print() {
		cout << "real:" << real << "	imag:" << imag << endl;
	}

};
int main() {
	Complex b(3.3);	//转换构造函数yongyu构造
	Complex c = b + 1;	//转换构造函数用于pipei自定义符号运算
	c.print();
}

2)系统预定义类型 < -  类类型

#include "iostream"
using namespace std;
class Complex {
private:
	double real;
	double imag;
public:
	Complex(double r, double i) :real(r), imag(i) {}	//构造函数

	operator double() {
		//将class转换为double
		// 
		//类可以转化成多种系统预定义类型         只能使用成员函数,不能使用友元函数
		//没有参数,但有返回值 (          不需要指定返回值的类型         )

		return real;
	}

	friend Complex operator+(const Complex& c1, const Complex& c2) {	//友元符号转换
		return Complex(c1.real + c2.real, c1.imag + c2.imag);
	}

	void print() {
		cout << "real:" << real << "	imag:" << imag << endl;
	}

};
int main() {
	Complex a( 1.1 , 2.2 );	
	cout<< a + 1;	//转换函数用于pipei相应的运算
}

类可以转化成多种系统预定义类型         只能使用成员函数,不能使用友元函数

没有参数,但有返回值 (          不需要指定返回值的类型         )

  • 14
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值