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

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

作者: 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;
    }
    ``

    相关文章

      网友评论

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

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