Effective C++条款37
2015-06-02 08:48
351 查看
不要重复定义virtual 函数中的参数缺省值,如果重复定义,会出现程序调用过程超乎常理的结果。
大家看如下代码:
我们肯定为结果的出乎意料而苦恼,想不通为什么会出现这种现象。在这里我做一个简单地解释。首先,大家要明白静态绑定和动态绑定的区别。
我们的virtual函数是动态绑定的调用过程,它的调用决策者是实际指向的对象。而我们函数中缺省值的选定却是静态绑定,它的决策者是当前正在调用的对象类型。
我们看上面的例子,s指针是shape类的,实际指向Rectangle类的对象,调用Drew函数时由于Drew是virtual函数,所以调用Rectangle类中的Drew函数,可是选择的函数参数缺省值却是Shape类的。
大家看如下代码:
#include<iostream> using namespace std; class Shape { public: enum ShapeColor{Red,Green,Blue}; virtual void Drew(ShapeColor color=Red) { if (color == Red) cout << "Red" << endl; else if (color == Blue) cout << "Blue" << endl; else cout << "Green" << endl; } }; class Rectangle :public Shape { public: virtual void Drew(ShapeColor color=Green) { if (color == Red) cout << "Red" << endl; else if (color == Blue) cout << "Blue" << endl; else cout << "Green" << endl; } }; int main() { Shape *s = new Rectangle(); s->Drew();//调用结果打印Red,而不是Green。 return 0; }
我们肯定为结果的出乎意料而苦恼,想不通为什么会出现这种现象。在这里我做一个简单地解释。首先,大家要明白静态绑定和动态绑定的区别。
我们的virtual函数是动态绑定的调用过程,它的调用决策者是实际指向的对象。而我们函数中缺省值的选定却是静态绑定,它的决策者是当前正在调用的对象类型。
我们看上面的例子,s指针是shape类的,实际指向Rectangle类的对象,调用Drew函数时由于Drew是virtual函数,所以调用Rectangle类中的Drew函数,可是选择的函数参数缺省值却是Shape类的。
相关文章推荐
- 《C++语言基础》程序阅读——标准输入输出对象及文本文件
- c++ 动态数组
- C++实现RTMP协议发送H.264编码及AAC编码的音视频
- C++实现RTMP协议发送H.264编码及AAC编码的音视频
- C++ 常用代码001 IsValidFileName VC/MFC 判断有效文件名
- C/C++内存分配
- C语言 文件I/O:实现结构体数据 存储到文件和从文件读取
- Count Primes [leetcode]
- C++中的位运算&和|
- hdoj1003注意在寻找最优解对应的时候寻找的顺序
- 6.1学习内容 ndk编程释放内存,C语言中char*添加字符得方法,java二维数组的读取与生成
- C++对象模型之编译器如何处理函数返回一个对象
- win7环境配置VC++6.0,让你的IDE飞起来
- 【C语言】指针
- [LeetCode] Linked List Cycle
- 面向对象程序设计-C++ Inheritance & Multiple inheritance & RTTI【第十三次上课笔记】
- 黑马程序员——C语言基础——指针编程练习题
- private:c/c++ 我的一些容易出错的地方 =>持续更新
- C++ 不用 < > 与 : ?运算符判断 a,b大小
- c++学习的50条忠告