c++ - 在非默认构造函数中使用默认构造函数
问题描述
重载构造函数时,是否可以让非默认构造函数调用默认构造函数,这样我就不会将默认构造函数中的代码复制粘贴到任何以后的非默认构造函数中?或者不允许此功能的原因是什么?
这是我的代码:
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++ 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;
}
推荐阅读
- javascript - 如何在 Google Chrome 版本 83.0.4103.61 上捕获输入日期的 Enter 键
- python - Python矢量化图像处理中的嵌套for循环
- react-native - Azure App Center - 错误 `fsevents` 不可用(此观察程序只能在 Darwin 上使用)。使用 --verbose 标志运行 CLI 以获取更多详细信息
- javascript - 如何比较对象数组和嵌套对象数组?
- azure - 从 azure devops 中的构建工件中排除 web.config 文件,在 iis 上进行 aap 部署
- python-3.x - Python Scrapy:全局变量不会在函数下更改其值
- sql - sql ex ru excercise 数据不匹配问题 63
- python - 考拉 applymap 将所有数据移动到单个分区
- woocommerce - Dokan 添加新产品不在后端保存自定义字段
- javascript - 已创建信号集线器但服务器 OnConnected() 无法正常工作