子类从基类中继承下来了什么?

What is inherited from the base class?

子类从基类中继承下来了什么?

In principle, a derived class inherits every member of a base class except:

原则上讲,子类继承了父类中所有的成员,除了以下:
  • its constructor and its destructor 
  • 构造器和析构器
  • its operator=() members
  • 赋值运算符重载函数
  • its friends
  • 友元

Although the constructors and destructors of the base class are not inherited themselves, its default constructor (i.e., its constructor with no parameters) and its destructor are always called when a new object of a derived class is created or destroyed.
尽管基类的构造器和析构器本身不能被继承,但是它默认构造器(比如无参的)和析构器总是被调用,当派生类对象被创建和销毁时。
If the base class has no default constructor or you want that an overloaded constructor is called when a new derived object is created, you can specify it in each constructor definition of the derived class:
如果基类没有默认的构造器,或是派生类被创建时你想调用基类重载的构造器,你可以定义派生类构造器时指定父类的构造器,如下:
derived_constructor_name (parameters) : base_constructor_name (parameters) {...}

For example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// constructors and derived classes
#include <iostream>
using namespace std;

class mother {
  public:
    mother ()
      { cout << "mother: no parameters\n"; }
    mother (int a)
      { cout << "mother: int parameter\n"; }
};

class daughter : public mother {
  public:
    daughter (int a)
      { cout << "daughter: int parameter\n\n"; }
};

class son : public mother {
  public:
    son (int a) : mother (a)
      { cout << "son: int parameter\n\n"; }
};

int main () {
  daughter cynthia (0);
  son daniel(0);
  
  return 0;
}
mother: no parameters
daughter: int parameter
 
mother: int parameter
son: int parameter


Notice the difference between which  mother 's constructor is called when a new  daughter  object is created and which when it is a  son  object. The difference is because the constructor declaration of  daughter  and  son :

注意当一个女儿或是儿子对象创建时,母亲的构造器被调用时的不同。不同的原因是女儿和儿子的构造器声明不同。

1
2
daughter (int a)          // nothing specified: call default
son (int a) : mother (a)  // constructor specified: call this 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值