美文网首页
委托构造函数和继承构造函数

委托构造函数和继承构造函数

作者: arkliu | 来源:发表于2022-11-09 07:07 被阅读0次

委托构造函数

先来看下,我们类的构造函数不使用委托构造的情况

class AA{
    public:
        int first;
        int second;
        int third;
    
    AA() {}
    AA(int first) {
        this->first = first;
    }

    AA(int first, int second) {
        this->first = first;
        this->second = second;
    }

    AA(int first, int second, int third) {
        this->first = first;
        this->second = second;
        this->third = third;
    }
};    

可以看到上述的所有构造函数,存在重复代码

使用委托构造函数

class AA{
    public:
        int first;
        int second;
        int third;
    
    AA() {}
    AA(int first) {
        this->first = first;
    }

    AA(int first, int second) :AA(first){
        this->second = second;
    }

    AA(int first, int second, int third): AA(first, second) {
        this->third = third;
    }
};  

继承构造函数

class AA{
    public:
        int first;
        double second;
        string third;
    AA(int first, double second, string third) {
        this->first= first;
        this->second = second;
        this->third = third;
    }
};    

class Child :public AA {
    public:
        using AA::AA; // 使用using AA::AA;后,子类就可以直接使用父类的构造函数了
};

int main() {
    Child child(22, 3.14, "hello world");
    return 0;
}
``

相关文章

  • ★04.关于委托构造函数

    简单示例 普通情况 继承中 注意事项 委托构造函数与继承中的继承构造函数非同一概念。

  • ES5 和 ES6 继承比较:

    ES5构造函数和继承: ES6构造函数和继承:

  • Javascript如何实现继承

    构造函数继承 原型构造函数组合继承

  • c++11 继承构造函数和委托构造函数

    1 继承构造函数 1.1 为什么需要继承构造函数 子类为完成基类初始化,在C++11之前,需要在初始化列表调用基类...

  • kotlin基础-类

    一、类组成 1.主构造函数 参数类型写法的三种情况: 2.次构造函数 次构造函数需要委托给主构造函数(直接委托或者...

  • 继承中执行顺序讨论

    继承中,子父类的构造函数(构造函数不被继承)1.子类必须调用父类的构造函数(构造函数不被继承)(1)如果没有写调用...

  • JavaScript的构造函数扩展、继承以及封装

    构造函数的扩展 扩展Man构造函数 构造函数的继承 Dog 继承 Pig JavaScript 内置对象的扩展 例...

  • 浅谈javaScript继承

    原型和构造函数 prototype属性对Object添加属性和方法 构造函数实例化过程 原型和继承 简单继承 继承

  • js继承

    1、原型式继承:借助构造函数的原型对象实现继承,即 子构造函数.prototype = 父构造函数.prototy...

  • 继承方法

    构造函数/原型/实例的关系 借助构造函数实现继承 借助原型链实现继承(弥补构造函数实现继承不足) 组合方式(组合原...

网友评论

      本文标题:委托构造函数和继承构造函数

      本文链接:https://www.haomeiwen.com/subject/mteazrtx.html