C++继承场景下'use of deleted function'报错的解决方法
报错根源
你给student和sports类自定义了参数化构造函数后,C++编译器不会再自动生成默认无参构造函数。子类构造时默认会调用父类的无参构造,而test继承自student、result继承自test和sports,所有中间子类和最终子类都没有显式调用父类的参数化构造,就触发了找不到对应构造函数的报错。
修改方案
需要给每一层子类都添加参数化构造函数,显式调用父类的参数化构造,把参数逐层传递,最终创建result对象时一次性传入所有父类需要的参数即可。
修改后完整代码
#include <iostream> using namespace std; class student { protected: string name; int roll; int age; public: student(string n, int r, int a) { name = n; roll = r; age = a; } }; class test : public student { protected: int sub[5]; public: // 新增参数化构造,显式调用父类student的构造 test(string n, int r, int a) : student(n, r, a) {} void marks() { cout << "Enter marks in 5 subjects: " << endl; cin >> sub[0] >> sub[1] >> sub[2] >> sub[3] >> sub[4]; } void display() { cout << "Name : " << name << "\nRoll number : " << roll << "\nAge: " << age << endl; cout << "Marks in 5 subjects : " << sub[0] << ", " << sub[1] << ", " << sub[2] << ", " << sub[3] << ", " << sub[4] << endl; } }; class sports { protected: int sportmarks; public: sports(int sm) { sportmarks = sm; } }; class result : public test, public sports { int tot; float perc; public: // 新增参数化构造,同时调用两个父类test和sports的构造 result(string n, int r, int a, int sm) : test(n, r, a), sports(sm) {} void calc() { tot = sportmarks; for(int i = 0; i < 5; i++) tot = tot + sub[i]; perc = (tot / 600.0) * 100; cout << "Total: " << tot << "\nPercentage: " << perc << endl; } }; int main() { // 直接通过参数化构造创建result对象,传入所有需要的参数 result ob("Name", 781, 19, 78); ob.marks(); ob.display(); ob.calc(); return 0; }
说明
- 不需要单独创建
student和sports的独立对象,所有父类的成员会通过继承链包含在result对象中 - 全程使用参数化构造函数创建对象,符合练习要求
内容的提问来源于stack exchange,提问作者Aniki
相关产品推荐
相关产品推荐

