首页 > 解决方案 > C++ 中的类不存在默认构造函数

问题描述

我已经创建了一个构造函数,但是为什么仍然有一个错误“类没有默认构造函数”?我已经搜索了这个问题的答案,但我仍然不清楚这个错误。有人能帮我吗?

pragma once
#include<string>
using namespace std;
class Date
{
private:
    int month;
    int day;
    int year;
public:
    Date(int newmonth, int newday, int newyear)
    {
        month = newmonth;
        day = newday;
        year = newyear;
    }
};
class Student
{
private:
    string name;
    Date birthDay;
    int score;
public:
    Student(string newname, Date newbirthDay, int score)
    {

    }
};

标签: c++constructor

解决方案


在 Student 中,您需要将Date birthDay变量初始化为构造函数初始化列表的一部分,否则它将尝试使用不存在的默认构造函数对其进行初始化。例子:

Student(string newname, Date newbirthDay, int score) : name(newname), birthDay(newbirthDay), score(score) {
}

通常,您应该使用初始化列表(与您的Date班级相同)。

在不相关的说明中,您应该考虑通过传递对象const &,即:

Student(const string &newname, const Date &newbirthDay, int score) : name(newname), birthDay(newbirthDay), score(score) {
}

推荐阅读