C++编程调试秘笈----读书笔记(1)
一、编译时的错误捕捉
经典的隐式类型转换问题:
[cpp]
#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对象,这是不正确的。为了防止这类隐式转换的问题,加上修饰符即可
[cpp]
#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;
}
这样在运行的时候,编译器就会提示错误。
那么如果真要使用=:
[cpp]
#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;
}
关于枚举的:
[cpp]
#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;
}
但是现在接受的却不是我们想要的类型,所以不建议使用枚举创建整型常量,而是用他们创建新类型:
[cpp]
#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;
}
补充:软件开发 , C++ ,