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

C++虚函数带有默认参数的问题

2014-01-06 22:31 441 查看
此问题在Effective
C++ 条款38: 决不要重新定义继承而来的缺省参数值中有描述

例:

#include <iostream>

#include <string>

//using namespace std;

class Base

{

public:

virtual void display(const std::string& strShow = "I am Base class !")

{

std::cout << strShow << std::endl;

std::cout << "Base display" << std::endl;

}

virtual ~Base(){}

};

class Derive: public Base

{

public:

virtual void display(const std::string& strShow = "I am Derive class !")

{

std::cout << strShow << std::endl;

std::cout << "Derive display" << std::endl;

}

virtual ~Derive(){}

};

int main()

{

Base* pBase = new Derive();

Derive* pDerive = new Derive();

pBase->display();

pDerive->display();

delete pBase;

delete pDerive;

getchar();

return 0;

}

结果:



I am Base class !

Derive display

I am Derive class!

Derive display

解析:

因为虚函数和默认参数的绑定方式不同。

虚函数为动态绑定,而默认参数静态绑定。

在使用父类指针指向的对象调用虚函数时,函数会按实际指向的对象调用对应的成员函数(动态绑定的结果),

而函数的默认参数依旧为父类对象中的默认参数(静态绑定的结果)。

如例所示,调用的方法不同,而输出的默认参数值相同。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: