首页 > 解决方案 > 在非默认构造函数中使用默认构造函数

问题描述

重载构造函数时,是否可以让非默认构造函数调用默认构造函数,这样我就不会将默认构造函数中的代码复制粘贴到任何以后的非默认构造函数中?或者不允许此功能的原因是什么?

这是我的代码:

class Test{
    private:
        int age;
        int createdAt;
    public:
        //Here is the defualt constructor.
        Test(){
            this->createdAt = 0;
        };
        //Non-default constructor calling default constructor.
        Test(int age){
            this->Test(); //Here, call default constructor.
            this->age = age;
        };
};

请注意,此代码会引发编译器错误“Invalid use of Test::Test”,所以我显然做错了什么。

谢谢你的时间!

标签: c++c++11

解决方案


是的,在委托构造函数的帮助下是可能的。这个特性称为构造器委托,是在 C++ 11 中引入的。看看这个,

#include<iostream>  
using namespace std;
class Test{
    private:
        int age;
        int createdAt;
    public:
        //Here is the defualt constructor.
        Test(){            
            createdAt = 0;
        };

        //Non-default constructor calling default constructor.
        Test(int age): Test(){ // delegating constructor
            this->age = age;
        };

        int getAge(){
            return age;
        }

        int getCreatedAt(){
            return createdAt;
        }
};

int main(int argc, char *argv[]) {
    Test t(28);
    cout << t.getCreatedAt() << "\n";
    cout << t.getAge() << "\n";
    return 0;
}

推荐阅读