需要在构造函数调用,继承类中进行解释吗? [英] Need explanation in constructor calling, in- inherited classes?

查看:106
本文介绍了需要在构造函数调用,继承类中进行解释吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
using namespace std;
 
class A
{
public:
  A()  { cout << "A's constructor called" << endl; }
};
 
class B
{
public:
  B()  { cout << "B's constructor called" << endl; }
};
 
class C: public B, public A  // Note the order
{
public:
  C()  { cout << "C's constructor called" << endl; }
};
 
int main()
{
    C c;
    return 0;
}





我的问题是为什么当我制作c类对象时,B / A类构造函数会自动调用





输出是



My question is why class B/A constructor is calling automatically when I make class c's object


output is

B's constructor called
A's constructor called
C's constructor called





我尝试过:



google.com和stackoverflow.com



What I have tried:

google.com and stackoverflow.com

推荐答案

C是从A和B派生的 - 所以在C的构造函数可以执行之前, A和B的构造函数都必须完成。如果不是这样,那么C构造函数就不能依赖它的基类提供的任何东西。



例如,假设A包含一个项目列表是从其构造函数中的数据库创建和归档的。 A的所有实例都可以依赖列表完成,因为构造函数必须在实例可用于其余代码之前完成。但是C也是A - 它的衍生方式与福特也是汽车的方式相同 - 所以它可能想要访问该列表。构造实例时,基类构造函数会在派生类之前自动调用,以确保在派生构造函数启动时所有内容都已准备就绪。



例如,稍微改变你的代码:

C is derived from both A and B - so before the constructor for C can be executed, the constructors for A and B must both be completed. If that wasn't the case, then teh C constructor could not rely on anything that its base classes provided.

For example, suppose A contained a list of items which is created and filed from a database in its constructor. All instances of A can rely on the list being complete because the constructor has to be finished before the instance is available to the rest of the code. But C is also an A - it derives from it in the same way that "a Ford" is also "A Car" - so it may well want to access that list. When you construct an instance, the base class constructors are automatically called before the derived classes to ensure that everything is ready for action when the derived constructor starts.

For example, change your code slightly:
class A
{
public:
A() { cout << "A's constructor called" << endl; }
};

class B: public A
{
public:
B() { cout << "B's constructor called" << endl; }
};

class C: public B
{
public:
C() { cout << "C's constructor called" << endl; }
};

int main()
{
C c;
return 0;
}

你会得到:

and you will get:

A's constructor called
B's constructor called
C's constructor called  

因为基类构造函数在执行派生之前都已完成。

Because the base class constructors are all completed before the derived ones are executed.


这篇关于需要在构造函数调用,继承类中进行解释吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆