c++基类和父类的空间分配是按照什么顺序进行的
PHP中文网
PHP中文网 2017-04-17 13:27:52
0
2
730

我知道constructor是先基类,下面这段代码可以用父类的成员变量给基类赋值,是不是先为父类分配变量空间?

#include<iostream>
using namespace std;

class Base{
public:
    Base(int& a) :_base_a(a){ cout << "Base:"<<endl; }
    virtual ~Base(){};
private:
    int& _base_a;

};
class Parent : public Base{
public:
    Parent() :Base(_par_a){ cout << "Parent: "<<endl; }
    int _par_a;
};
void main(){
    Parent p;
    p._par_a = 1;
}
PHP中文网
PHP中文网

认证高级PHP讲师

reply all(2)
巴扎黑

Allocating space precedes initialization. Space allocation is completed first, and then member variables are initialized.

PHPzhong

When you construct a p, C++ first opens up a space of sizeof(Parent), and then executes Base(_par_a) first. But _par_a has not been initialized at this time, so the value inside is uncertain. You can try printing the passed in value in the Base constructor.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!