C++虚函数带有默认参数的问题
来源:互联网 发布:windows怎么打开pages 编辑:程序博客网 时间:2024/05/16 17:04
此问题在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
解析:
因为虚函数和默认参数的绑定方式不同。
虚函数为动态绑定,而默认参数静态绑定。
在使用父类指针指向的对象调用虚函数时,函数会按实际指向的对象调用对应的成员函数(动态绑定的结果),
而函数的默认参数依旧为父类对象中的默认参数(静态绑定的结果)。
如例所示,调用的方法不同,而输出的默认参数值相同。
- C++虚函数带有默认参数的问题
- C++ 带有默认参数的虚函数
- C++里面的重写带有默认参数的虚函数的问题
- 带有默认参数的构造函数
- 【C++】实现一个复数类(complex)(带有默认参数的构造函数 )
- 【C++总结】带有默认参数的函数,缺省函数
- C#---带有参数的构造函数
- C++之带有默认参数值的构造函数
- javascript中使用带有默认参数的自定义构造函数
- C++之带有默认参数值的构造函数
- 虚函数默认参数的问题记录
- 虚函数的默认参数问题
- 虚函数的默认参数问题
- C++虚函数的默认参数问题
- 深入 Qt5 信号槽新语法 重载函数 函数指针 c/c++风格类型转换 带有默认参数的槽函数
- C++_有默认参数的函数
- 带有参数的main函数
- 虚函数的默认参数
- 做个小项目——温控仪
- A Distributed Mutex based on Redis
- hudson pending - Waiting for next available executor
- VS2010 打开并能编译VS2012项目的解决方法-----(VS2005,vs2008类似处理方法)
- 音频解码详解
- C++虚函数带有默认参数的问题
- SQOOP
- WAP 2.0介绍和使用规范
- Adaboost应用系列之三:Opencv2.4.X中利用Adaboost训练HOG特征产生xml分类器
- wpa_supplicant 笔记
- poj 1850
- SqlServer格式化时间
- Div的框架学习
- loading黑马程序员之高级编程:枚举(4-1)