简体   繁体   English

在C ++中继承的构造函数

[英]constructors inherited in c++

Excerpt from here: 从这里摘录:

Constructors are different from other class methods in that they create new objects, whereas other methods are invoked by existing objects. 构造函数与其他类方法的不同之处在于它们创建新对象,而其他方法则由现有对象调用。 This is one reason constructors aren't inherited. 这是构造函数不被继承的原因之一。 Inheritance means a derived object can use a base-class method, but, in the case of constructors, the object doesn't exist until after the constructor has done its work. 继承意味着派生的对象可以使用基类方法,但是对于构造函数,该对象直到构造函数完成工作后才存在。

  1. Does a constructor create new object or when a object is called the constructor is called immediately? 构造函数是否创建新对象,或者在调用对象时立即调用该构造函数?

  2. It is said that a constructor and destructor is not inherited from the base class to the derived class but is the program below a contradiction, we are creating an object of the derived class but it outputs constructor and destructor of the base class also? 据说构造函数和析构函数不是从基类继承到派生类,而是程序处于矛盾之下,我们正在创建派生类的对象,但它也输出基类的构造函数和析构函数?


class A{
public:
    A(){
        cout<< Const A called<<endl;
    }
    ~A(){
        cout<< Dest A called <<endl;
    }
};

Class B : public A{
public:
    B(){
        cout<< Const B called <<endl;
    }
    ~B(){
        cout<< Dest B called <<endl;
    }
};

int main(){
    B obj;
    return 0;
}

Output: 输出:

Const A called const A被称为

Const B called const B叫

Dest B called 目的地B叫

Dest A called 目的地A被称为

A derived class D does not inherit a constructor from B in the sense that, specifying no explicit D constructors I can use my B(int) like to construct a new D(1); 从某种意义上说,派生类D不会从B继承构造函数,因为不指定任何显式D构造函数,我可以使用B(int)来构造new D(1); .

However, what I can do is use a base class constructor in the definition of a derived class constructor, like D::D(void) : B(1) {} . 但是,我可以做的是在派生类构造函数的定义中使用基类构造函数,例如D::D(void) : B(1) {}

Less abstract, suppose I have a constructor for Person that takes a gender parameter, I might wish to create a: 不太抽象的是,假设我有一个使用gender参数的Person构造函数,我可能希望创建一个:

class Son: Person{
public:
    Son(void) : Person(male) {};
};

to construct a Son , which is obviously a Person , but certainly doesn't need parameterised gender . 构造一个Son ,显然是一个Person ,但是当然不需要参数gender

Destructors are 'inherited' in the sense that on the closing brace of D::~D(){} a call to ~B() is implied. 析构函数在意义上的“继承”上的闭括号D::~D(){}到呼叫~B()是隐含的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM