C++编译错误:Auto类无默认构造函数,如何正确引用类对象?
解决C++类关联对象时的编译错误:
no matching function for call to 'Auto::Auto()' 错误原因
在AutoHuur类里声明Auto wagen;和Klant huur;作为成员变量时,创建AutoHuur对象的第一步,编译器会自动调用这两个成员的无参默认构造函数。但你的Auto类只定义了带参数的构造函数,没有提供无参版本;Klant类同样只有带参构造,没有默认构造,所以编译器找不到匹配的构造函数,触发报错。
两种修复方案
方案1:用成员初始化列表直接初始化成员对象
修改AutoHuur的构造函数,在函数体前用初始化列表直接完成wagen和huur的初始化,跳过默认构造的调用,这也是C++中初始化成员对象的推荐方式,效率更高。
class AutoHuur{ private: int aantal_dagen; Auto wagen; Klant huur; public: // 成员初始化列表直接初始化成员 AutoHuur(Auto car, Klant huurder, int dagen) : wagen(car), huur(huurder), aantal_dagen(dagen) {} };
方案2:给Auto和Klant添加默认构造函数
如果需要允许无参创建这两个类的对象,可以给它们补充无参构造:
class Auto{ private: string type; double prijs_per_dag; public: // 默认无参构造 Auto() : type(""), prijs_per_dag(0.0) {} // 原带参构造 Auto(string type, double prijs_per_dag){ this->type = type; this->prijs_per_dag = prijs_per_dag; } // 其他成员函数不变 }; class Klant{ private: string naam; double korting_percentage; public: // 默认无参构造 Klant() : naam(""), korting_percentage(0.0) {} // 原带参构造 Klant(string naam): naam(naam){} // 其他成员函数不变 };
这样AutoHuur原来的构造函数就能正常运行,编译器会先调用默认构造创建成员,再执行赋值操作。
完整修正代码(方案1示例)
#include <iostream> #include <string> // 注意:原代码缺少string头文件,必须添加否则编译报错 using namespace std; class Auto{ private: string type; double prijs_per_dag; public: Auto(string type, double prijs_per_dag){ this->type = type; this->prijs_per_dag = prijs_per_dag; } void set_prijs_per_dag(double percentage){ this->prijs_per_dag = percentage; } double get_prijs_per_dag(){ return prijs_per_dag; } }; class Klant{ private: string naam; double korting_percentage; public: Klant(string naam): naam(naam){} void set_korting(double percentage){ this->korting_percentage = percentage; } double get_korting(){ return this->korting_percentage; } string get_name(){ return naam; } void set_name(string naam){ this->naam = naam; } }; class AutoHuur{ private: int aantal_dagen; Auto wagen; Klant huur; public: AutoHuur(Auto car, Klant huurder, int dagen) : wagen(car), huur(huurder), aantal_dagen(dagen) {} }; int main(){ Klant k("Mijnheer de Vries"); k.set_korting(10.0); Auto a1("Peugeot 207", 50); AutoHuur ah1(a1, k, 4); }
内容的提问来源于stack exchange,提问作者kinggoid games
相关产品推荐
相关产品推荐

