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
解析:
因为虚函数和默认参数的绑定方式不同。
虚函数为动态绑定,而默认参数静态绑定。
在使用父类指针指向的对象调用虚函数时,函数会按实际指向的对象调用对应的成员函数(动态绑定的结果),
而函数的默认参数依旧为父类对象中的默认参数(静态绑定的结果)。
如例所示,调用的方法不同,而输出的默认参数值相同。
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++中 虚函数中的默认参数问题
- C++ 虚函数的缺省参数问题
- C++之带有默认参数值的构造函数
- C++ 带有默认参数的虚函数
- C#调用C++编写的DLL函数各种参数传递问题
- 关于OpenCV图像操作的默认参数问题
- c++ 构造函数的默认参数
- C/C++ 参数载入问题
- jmeter从外部文件取值问题,如果文件中的参数值为纯数字形式的,jmeter会默认将其识别成int型数据
- [c++]子类私有的虚函数,多态问题
- C++二维数组作为参数问题
- C#调用C++编写的DLL函数各种参数传递问题
- 类模板相互引用的问题(错误:缺少类型说明符-假定为int。注意:C++不支持默认int)
- 关于C++中私有继承后虚函数的访问权限与私有继承后多态的问题
- C/C++函数指针参数不匹配问题
- C++中数组以及多维数组作为函数参数时的一些问题
- 线程调用带有参数的委托(用来解决跨线程调用控件的问题)