如何在C++中使用拷贝构造函数输出类变量及解决cargo类编译报错
问题修复与实现说明
1. 解决 No matching function for call to 'cargo::cargo()' 报错
报错原因:当类中显式声明了任意构造函数(如你编写的拷贝构造函数),C++ 会停止自动生成默认无参构造函数 cargo()。main 函数中 cargo shipment; 语句需要调用这个无参构造,因此触发报错。
修复方法:在 cargo 类的 public 访问区域添加默认无参构造的声明:
cargo() = default; // 显式要求编译器生成默认无参构造,支持C++11及以上标准
如果使用旧版编译器,可替换为手动空实现:
cargo() {}
2. 修正现有拷贝构造函数的漏洞
你编写的拷贝构造函数遗漏了私有成员 aircraft 的拷贝,修正后的完整实现:
cargo::cargo(const cargo& other){ unit = other.getUnit(); abbrev = other.getAbbrev(); unitID = other.getUnitID(); aircraft = other.getAircraft(); // 补充遗漏的aircraft成员拷贝 weight = other.getWeight(); destination = other.getDestination(); // 可选:添加打印语句,直观验证拷贝构造函数已执行 cout << "拷贝构造函数已触发" << endl; }
额外修正:类中声明的 friend int weightConvert(int weightName); 与实际定义的 double weightConvert(double) 类型不匹配,可直接删除这个无用的友元声明。
注:你编写的 setDestinatoin 方法名存在拼写错误(少写字母n,应为setDestination),不影响当前逻辑,后续扩展功能时可修正。
3. 拷贝构造函数的调用规则
拷贝构造函数不需要手动调用,也无需额外编写 void copy(); 这类成员方法,它会在用一个已有同类型对象初始化新对象时自动触发,常见触发场景:
- 直接初始化新对象:
cargo copiedShipment(shipment); - 同类型赋值初始化:
cargo copiedShipment = shipment;
4. 拷贝结果展示实现
完成原对象的输入输出后,触发拷贝构造生成新对象,再调用新对象的 output() 方法即可,修正后的 main 函数示例:
int main(){ cout << "=== 输入原货运信息 ===" << endl; cargo shipment; shipment.input(); cout << "\n=== 原货运内容 ===" << endl; shipment.output(); cout << "\n=== 执行拷贝 ===" << endl; cargo copiedShipment = shipment; // 此处自动调用拷贝构造函数 cout << "\n=== 拷贝得到的货运内容 ===" << endl; copiedShipment.output(); return 0; }
内容的提问来源于stack exchange,提问作者pancakex62
相关产品推荐
相关产品推荐

