您的位置:首页 > 编程语言 > C语言/C++

Effective C++条款37

2015-06-02 08:48 351 查看
不要重复定义virtual 函数中的参数缺省值,如果重复定义,会出现程序调用过程超乎常理的结果。

大家看如下代码:

#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类的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: