【发布时间】:2014-05-12 15:20:14
【问题描述】:
我有 4 个重载函数 vfoo(3 个是虚拟的)
我在这里尝试测试几个概念:
- 使用虚函数重载
- 当派生类实现了自己的重载函数版本时,重载函数隐藏在派生类中。
- 基类指针存储派生类对象时的行为是什么
- 派生类中的重载函数,如 void vfoo(char x)
#include<iostream>
using namespace std;
/*Base class having 4 overloaded function*/
class ClassBaseV
{
public:
virtual void vfoo( int x ) {
cout << "ClassBaseV vfoo(int), x = " << x << endl;
}
virtual void vfoo( double x ) {
cout << "ClassBaseV vfoo(double), x = " << x << endl;
}
virtual void vfoo( int x, double y ) {
cout << "ClassBaseV vfoo(int,double), x = " << x << ", y = " << y << endl;
}
void vfoo( double x, int y ) {
cout << "ClassBaseV vfoo(double,int), x = " << x << ", y = " << y << endl;
}
};
class ClassDerived1 : public ClassBaseV
{
public:
//Overloaded with char x
void vfoo( char x ) {
cout << "ClassDerived1 vfoo(char), x = " << x << endl;
}
//over riding int x
void vfoo( int x ) {
cout << "ClassDerived1 vfoo(int), x = " << x << endl;
}
};
int main()
{
ClassBaseV *cB = new ClassDerived1(); /*Base pointer storing derived class object*/
ClassDerived1 *cd1 = new ClassDerived1(); //Derived class object
cd1->vfoo('a');//Direct call using derived class object. this works
char a = 'a';
cB->vfoo(a); // trying to call char x using cB. This calls derived class int How?
cB->vfoo(10); // trying to call int x using CB. This calls derived class int
cB->vfoo(2.2); // Wanted this to not to work as base class overloaded functions are hidden but this works
return 1;
}
【问题讨论】:
-
输出 ClassDerived1 vfoo(char), x = a ClassDerived1 vfoo(int), x = 97 ClassDerived1 vfoo(int), x = 10 ClassBaseV vfoo(double), x = 2.2
-
如果你实现了重载集的某些功能,通常的做法是添加一个 using 声明,让其他功能进入作用域。避免令人尴尬的使用失败...
标签: c++