自动类型转换

对于自动类型转换,最常见的就是 混合运算 以及 赋值运算,还有一种就是函数值的类型转换

  1. 赋值运算:自动把“=”右边的表达式的类型转换成“=”右边的变量的类型,例如 int a=4.5; a的值实际是4!

 

  1. 混合运算:就是一个运算表达式当中包含了多个类型,这时候就需要有类型转换。当运算符两边的操作数类型不同时,其中一个操作数就要经过类型转换以和另一个操作数的类型相一致,然后才能进行运算。
    变换操作数采取就高不就低的原则,即级别低的操作数先被转换成和级别高的操作数具有同一类型,然后再进行运算,结果的数据类型和级别高的操作数相同。
           高        double    ←←    float
           ↑          ↑             
           ↑         long     
           ↑          ↑
           ↑        unsigned
           ↑          ↑
           低         int      ←←    char,short
  2.              自动转换顺序表

	int i = 0;
	i = 4.5 * 5;
	cout << i << endl; //22

	unsigned int i = 10;
	int j = -1;
	if (i > j)
	{
		cout << "yes" << endl;
	}
	else
	{
		cout << "no" << endl;
	}

输出no



  1. 函数返回值的类型转换: int f1(){ return 36.8;}

ubuntu 64位机器测试结果

#include <iostream>
using namespace std;
int main()
{
        cout << sizeof(double) << endl;
        cout << sizeof(long) << endl;
        cout << sizeof(float) << endl;
        cout << sizeof(unsigned) << endl;
        cout << sizeof(int) << endl;
        cout << sizeof(char) << endl;
        cout << sizeof(short) << endl;
        cout << sizeof(char*) << endl;
        int i;
        i = 3.14 + 'a';

}


8
8
4
4
4
1
2
8



windows 32位操作系统

#include <iostream>
using namespace std;

int main()
{
	cout << sizeof(double) << endl;		//8
	cout << sizeof(long) << endl;		//4
	cout << sizeof(float) << endl;		//4
	cout << sizeof(unsigned) << endl;	//4
	cout << sizeof(int) << endl;		//4
	cout << sizeof(char) << endl;		//1
	cout << sizeof(short) << endl;		//2
	cout << sizeof(char*) << endl;		//4
	int i;
	i = 3.14 + 'a';

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值