类型转换函数

#include <iostream>
#include <string>

using namespace std;

int main()
{   
    short s = 'a';
    unsigned int ui = 1000;
    int i = -2000;
    double d = i;
    
    cout << "d = " << d << endl;
    cout << "ui = " << ui << endl;
    cout << "ui + i = " << ui + i << endl;//i ==> ui
    
	
    if( (ui + i) > 0 )
    {
        cout << "Positive" << endl;
    }
    else
    {
        cout << "Negative" << endl;
    }
    
    cout << "sizeof(s + 'b') = " << sizeof(s + 'b') << endl;//int + int,int高效
    
	
    return 0;
}


在这里插入图片描述

转换构造函数

  • 1.有且仅有一个参数
  • 2.参数是基本类型
  • 3.参数是其他类类型

explicit关键字杜绝编译器的转换尝试

  • explicit修饰的函数只能显示转换
  • static_cast(value)
  • (ClassName)(value)
#include <iostream>
#include <string>

using namespace std;

class Test
{
    int mValue;
public:
    Test()
    {
        mValue = 0;
    }

    explicit Test (int i)//转换构造函数1.有且仅有一个参数2.参数是基本类型3.参数是其他类型
    {
		mValue = i;
    }
	Test operator + (const Test& p)//重载加法操作符函数
	{
		Test ret(mValue + p.mValue);
		return ret;
	}
	int value()
	{
		return mValue;
	}
};

int main()
{   
    Test t;
    
	t = static_cast<Test>(5);//临时对象  ==> t = Test(5);
    
	Test r;
	
	r = t + static_cast<Test>(10);  // r = t + Test(10);  重载函数
	
	cout << r.value() << endl;
	
    return 0;
}

转换构造函数

  • 1.有且仅有一个参数
  • 2参数是其他类类型
  • 3.类型装换时被调用
  • explicit杜绝隐式类型转换

类类型转换函数

#include <iostream>
#include <string>

using namespace std;

class Test
{
	int mValue;
public:
	Test(int i = 0)
	{
		mValue = i;
	}
	int value()
	{
		return mValue;
	}
	operator int()//类类型转换函数
	{
		int ret = mValue;
		return mValue;
	}
};

int main()
{   
	Test t(100);
	int i = t;//==>>int i = t.operator int();
	
    cout << "t.value() = " << t.value() << endl;
	cout << "i = " << i << endl; 
    return 0;
}

类转类型函数

#include <iostream>
#include <string>

using namespace std;

class Test;

class Value
{
public:
		Value()
		{
			
		}
		explicit Value(Test& t)
		{
			
		}
};

class Test
{
	int mValue;
public:
	Test(int i = 0)
	{
		mValue = i;
	}
	int value()
	{
		return mValue;
	}
	//operator Value()//类类型转换函数
	Value toValue()
	{
		Value ret;
		
		cout <<  "operator Value()" << endl;
		return ret;
	}
};

int main()
{   
	Test t(100);
	
	//Value v = t;//v= t.operator Value(); //==>Value(t) 
	//Value v = t.toValue();

    return 0;
}

小结

  • 类型转换函数会与转换构造函数冲突
  • 加入explicit 杜绝隐式转换
  • Value toValue()代替类型转换函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值