You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++实现Person类构造时报错no matching function for call to 'Date::Date()'

错误原因

  • 你自定义的Date类显式声明了带三个参数的构造函数Date(int day, int month, int year),这种情况下C++编译器不会自动生成无参的默认构造函数。
  • C++中类的非静态成员对象会在进入构造函数的函数体之前完成构造:你当前写的Person构造函数是在函数体内部对DateOfBirth做赋值操作,在执行赋值代码前,编译器已经尝试调用Date的无参构造函数来初始化DateOfBirth成员,找不到对应函数就抛出了这个错误。

修复方案

推荐使用成员初始化列表来初始化DateOfBirth成员,跳过无参构造的步骤,直接调用拷贝构造函数完成初始化,性能更高:

Person::Person(const string &name,
               const string &address,
               const Date &date) : Name(name), Address(address), DateOfBirth(date)
{
    // 函数体内不需要再写成员赋值逻辑
}

如果你的业务场景确实需要允许Date对象先默认构造再赋值,也可以给Date类补充无参构造函数,但该方案会多执行一次无参构造和一次赋值操作,效率低于初始化列表方案:

class Date
{
    public:
        Date() = default; // C++11及以上版本可直接用该写法,也可自行实现空逻辑的无参构造
        Date(int day, int month, int year);
        int GetYear() const;
    private:
        int Day;
        int Month;
        int Year;
};

内容的提问来源于stack exchange,提问作者TookieWookie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 09:54:03