C++编程调试秘笈----读书笔记(1)

一、编译时的错误捕捉

经典的隐式类型转换问题:

#include "stdafx.h"

class Apple
{

};
class Banana
{

};
class Orage
{
public:
	Orage(const Apple& apple);
//	Orage(const Apple& apple, const Banana *pBanana = 0);
};

Orage::Orage(const Apple& apple){}
Orage::Orage(const Apple& apple, const Banana *pBanana){}

int _tmain(int argc, _TCHAR* argv[])
{
	Apple	RedApple;
	Banana	GreenBanana;
	Orage	BlueOrage(RedApple);
//	Orage	BlueOrage(RedApple, &GreenBanana);
	Orage	BlueOrage = RedApple;

	return 0;
}

这里的问题出来了,可以让一个Apple对象直接赋值给Orage对象,这是不正确的。为了防止这类隐式转换的问题,加上修饰符即可

#include "stdafx.h"

class Apple
{

};

class Orage
{
public:
	explicit Orage(const Apple& apple);
};

Orage::Orage(const Apple& apple){}

int _tmain(int argc, _TCHAR* argv[])
{
	Apple	RedApple;
	Orage	BlueOrage(RedApple);
	Orage	BlueOrage = RedApple;

	return 0;
}

这样在运行的时候,编译器就会提示错误。

那么如果真要使用=

#include "stdafx.h"

class Apple
{
public:
	operator Orage() const
	{
		Apple mine;
		Orage toConvertOrage(mine);
		return toConvertOrage;
	};
};

class Orage
{
public:
	explicit Orage(const Apple& apple);
};

Orage::Orage(const Apple& apple){}

int _tmain(int argc, _TCHAR* argv[])
{
	Apple	RedApple;
	Orage	BlueOrage(RedApple);
	Orage	BlueOrage = RedApple;

	return 0;
}

关于枚举的:

#include "stdafx.h"

enum { SUM, MON, TUE, WED, THU, FRI, SAT };
enum { JAN = 1, FEB, MAR, APR, MAY, JUN };

void IOnlyAcceptWeekType(int WeekType)
{
}

int _tmain(int argc, _TCHAR* argv[])
{
	IOnlyAcceptWeekType(SUM);
	IOnlyAcceptWeekType(JAN);
	return 0;
}

但是现在接受的却不是我们想要的类型,所以不建议使用枚举创建整型常量,而是用他们创建新类型:

#include "stdafx.h"

typedef enum { SUM, MON, TUE, WED, THU, FRI, SAT } WeekType;
typedef enum { JAN = 1, FEB, MAR, APR, MAY, JUN } MonthType;

void IOnlyAcceptWeekType(WeekType weekType)
{
}

int _tmain(int argc, _TCHAR* argv[])
{
	IOnlyAcceptWeekType(SUM);
	IOnlyAcceptWeekType(JAN); // error
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值