一、编译时的错误捕捉
经典的隐式类型转换问题:
#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;
}