C++运算符重载时为何需同时保留默认与带参构造函数?
为什么Account类需要同时保留默认构造函数与带参构造函数?
直接原因:运算符重载中的默认初始化依赖默认构造函数
你的代码里,operator+重载函数中有这行关键代码:
Account OBJ2;
这是无参创建对象的默认初始化操作,必须调用类的默认构造函数才能完成。
C++有个核心规则:当你手动定义了任何构造函数(比如这里的带参构造Account(int a)),编译器就不会自动生成默认构造函数了。所以如果你删掉手动写的Account() {},Account OBJ2;这行就找不到可用的默认构造函数,直接触发编译错误。
带参构造函数的作用
main函数里的Account a(n1);和Account b(n2);是用整数参数初始化对象,这个逻辑全靠带参构造函数实现:它负责给balance赋值,同时计算对应的interest。如果没有这个带参构造函数,你没法用整数直接创建符合需求的Account对象。
可选的替代方案
如果不想保留默认构造函数,你可以修改operator+的实现,绕过默认初始化。比如新增一个能同时接收balance和interest的构造函数,直接用计算好的总值初始化新对象:
// 新增构造函数 Account(int b, int i) : balance(b), interest(i) {} // 修改operator+实现 Account operator+(Account &obj){ int total_balance = this->balance + obj.balance; int total_interest = this->interest + obj.interest; return Account(total_balance, total_interest); }
这样就不需要默认构造函数了,本质是用新的构造函数替代了默认构造的作用。
内容的提问来源于stack exchange,提问作者sm75
相关产品推荐
相关产品推荐

