【发布时间】:2017-08-02 20:37:28
【问题描述】:
我创建了基类指针并为其分配了新的派生类。
class Base
{
public:
virtual void f( int );
virtual void f( double );
virtual void g( int i = 10 );
};
void Base::f( int )
{
cout << "Base::f(int)" << endl;
}
void Base::f( double )
{
cout << "Base::f(double)" << endl;
}
void Base::g( int i )
{
cout << i << endl;
}
class Derived: public Base
{
public:
void f( complex<double> );
void g( int i = 20 );
};
void Derived::f( complex<double> )
{
cout << "Derived::f(complex)" << endl;
}
void Derived::g( int i )
{
cout << "Derived::g() " << i << endl;
}
void main()
{
Base b;
Derived d;
Base* pb = new Derived;
b.f(1.0);
d.f(1.0);
pb->f(1.0);
b->g();
d->g();
pb->g();
delete pb;
}
结果是:
Base::f(double)
Derived::f(complex)
Base::f(double)
10
Derived::g() 20
Derived::g() 10
b 和 d 的结果是预期的。 pb->f(1.0) 调用基函数 f(double),但 pb->g() 似乎调用派生类函数 g,但使用基类的参数 i=10。为什么?
【问题讨论】:
-
为什么?因为您静态使用
Base接口,所以向Derived::pb的分派仅在运行时发生。 -
delete pb;导致未定义的行为,因为 Base 没有虚拟析构函数
标签: c++ pointers derived-class virtual-functions