C++编程调试秘笈----读书笔记(1)
来源:互联网 发布:java字符文件乱码 编辑:程序博客网 时间:2024/06/05 17:56
一、编译时的错误捕捉
经典的隐式类型转换问题:
#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[]){AppleRedApple;BananaGreenBanana;OrageBlueOrage(RedApple);//OrageBlueOrage(RedApple, &GreenBanana);OrageBlueOrage = 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[]){AppleRedApple;OrageBlueOrage(RedApple);OrageBlueOrage = 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[]){AppleRedApple;OrageBlueOrage(RedApple);OrageBlueOrage = 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); // errorreturn 0;}
- C++编程调试秘笈----读书笔记(1)
- C++编程调试秘笈----读书笔记(2)
- C++编程调试秘笈----读书笔记(3)
- C++编程调试秘笈----读书笔记(4)
- C++编程调试秘笈----读书笔记(5)
- C++编程调试秘笈----读书笔记(6)
- 《C++编程调试秘笈》读后感
- C++编程调试秘笈(第1次阅读)
- c++编程调试秘笈笔记一
- 《C专家编程》读书笔记1
- C专家编程 读书笔记1
- 《C专家编程》读书笔记(1)
- 《C专家编程》读书笔记(1)
- 《Linux C编程一站式学习》 读书笔记(1)
- 《C专家编程》读书笔记:1~3章
- 【读书笔记】c专家编程
- 《C专家编程》读书笔记
- 《C专家编程》读书笔记
- 2012年年末_换了家公司_呆了半个月_毅然离职
- 配置eyeOS系统--3--安装mysql数据库和Apache服务器
- RL-RTX(CM3)的任务中不能配置NVIC,否则进入HardFault的原因
- Evolution3D引擎成果截图
- 我的2012 — 毕业半年,金融5个月
- C++编程调试秘笈----读书笔记(1)
- C++编程调试秘笈----读书笔记(2)
- 用旅行商算法制作艺术图像
- Python学习笔记
- osganimationeasemotion例子
- Fedora 17无法用root账户登录解决方法
- dbms_sql
- Leetcode: Searching an Element in a Rotated Sorted Array I
- 杭电Hd 2051 Bitset