09~C++类型转换

1. 类型转换定义

两种不同类型的数据进行运算,编译器会将其中一种类型转换为另一种类型

1.1 基本数据类型的类型转换

#include <iostream>
using namespace std;
int main(void) {
/*隐式转换允许规则*/
long count; //
count = 8; //int -> long int
double time; 
time  = 11; //int -> double
int side; // double -> int
side = 3.33; // double -> int
/*隐式转换规则不允许*/
//int *p = 10;

/*显示类型转换*/
count = (long) 8;
time = (double) 11;
side = (int)3.3;
int *p = (int*)10;
return 0;
}

2.2 类类型类型转换

2.2.1 函数形参和实参不同

#include <iostream>
#include <string>
using namespace std;
class Stack
{
public:
	Stack(void)
	{
		cout << "无参构造" << endl;
	}
	Stack(int i)
	{
		cout << "int转换Stack/单参构造" << endl;
	}
	
	Stack& operator= (Stack const& rhs)
	{
		cout << "赋值函数" << endl;
		return *this;
	}

	Stack (Stack const& that)
	{
		cout << "拷贝构造 " << endl;
	}
};
/*函数形参为"类"类型 Stack*/
void fool(Stack val)
{
}

int main(void) {
	
Stack stack;

/*参数为整形数字->把int转换为Stack类型,这是一种隐式类型转换*/
fool(1);
/*使用显式类型转换*/
fool(Stack(1));

/*参数为Stack对象->实参就是Stack类型,调用拷贝构造函数*/
fool(stack);
return 0;
}

2.2.2 “=”两侧类型不一致,编译器选择将右侧类型转换为左侧类型,然后拷贝给左侧变量

#include <iostream>
using namespace std;

struct Stack {
	Stack(void) {
		cout <<  "缺省构造函数" << endl;
	}
	Stack(int a ) {
		cout <<  "int->Stack 类型转换函数" << endl;
	}
	Stack(double b) {
		cout << "double->int 类型转换函数" << endl;
	}
	Stack(Stack const& that) {
		cout << "拷贝构造函数" << endl;
	}
	Stack& operator= (Stack const& that) {
		cout <<"赋值函数 " <<endl;
	}
};

int main(void) {
Stack s1;

/*case1 隐式类型转换*/
//先匿名构造一个Stack对象,然后使用赋值运算符=函数: 这就是隐式类型转换的本质
s1 = 2;
s1 = 3.3;

/*case1 显示类型转换,语法形式同隐式转换有区别,但过程是一样的*/
//新编译器语法
s1 = Stack(2);
s1 = Stack(3.3);
//旧编译器语法
s1 = (Stack)2;
s1 = (Stack)3.3;
return 0;
}

2.2.3 函数返回类型形参和实参类型不一致(读者有没有注意到,示例代码的错误呢?返回了栈中的对象…我懒得改了)

#include <iostream>
using namespace std;

struct Stack {
	Stack(void) {
		cout <<  "缺省构造函数" << endl;
	}
	Stack(int a ) {
		cout <<  "int->Stack 类型转换函数" << endl;
	}
	Stack(double b) {
		cout << "double->Stack 类型转换函数" << endl;
	}
	Stack(Stack const& that) {
		cout << "拷贝构造函数" << endl;
	}
	Stack& operator= (Stack const& that) {
		cout <<"赋值函数 " <<endl;
	}
};


Stack fool(void)
{	
	/*隐式调用 类型转换函数*/
	return 1;
}
Stack barn(void)
{
	/*显式调用 类型转换函数*/
	return Stack(3.3);
}
int main(void) {
fool();
barn();
return 0;
}

2.3 “类” 类型转换为基本类型

#include <iostream>
using namespace std;
struct Stack {
	operator int() {
		return 10;
	}
	explicit operator double() {
		return 9.9;
	}
	explicit Stack(void) {
	}
};
int main() {
Stack s1;
int i = s1;
double d = (double) s1;
return 0;
}

2. 总结

隐式类型转换一定要谨慎使用,从而避免产生错误的函数调用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值