gpt4 book ai didi

c++ - 分配给派生类的基类指针

转载 作者:行者123 更新时间:2023-11-30 03:33:34 24 4
gpt4 key购买 nike

我创建了基类指针并为其分配了新的派生类。

 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。为什么?

最佳答案

Kerrek SB 在评论中都说了,我会详细一点。

this answer ,解析默认函数参数的机制发生在编译时。当编译器看到 pb->g(); 时,知道 pbBase* 类型的指针,它会引用 的声明code>Base::g,即

virtual void g( int i = 10);

结论是:

1- 缺少的参数 i 应设置为 10。这是编译时的决定。

2- 该方法被声明为virtual,这意味着实际调用的方法取决于pb 在运行时将指向的内容。编译器设置机制以在运行时分派(dispatch)对 g 的调用(通常通过 vtable 的间接调用)。由于在运行时 pb 实际上指向类型为 Derived 的对象,因此调用方法 Derived::g

关于c++ - 分配给派生类的基类指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42753302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com