【问题标题】:no default constructor exists for class in C++ [duplicate]C ++中的类不存在默认构造函数[重复]
【发布时间】:2021-09-04 01:03:44
【问题描述】:

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

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


    【解决方案1】:

    默认构造函数需要一个空参数列表,因此在您的情况下它是 Date() 或 Student()

    【讨论】:

      【解决方案2】:

      在Student中,你需要将Date birthDay变量初始化为构造函数初始化列表的一部分,否则它会尝试用默认构造函数来初始化它,而默认构造函数并不存在。示例:

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

      一般来说,您应该使用初始化列表(对于您的 Date 类也是如此)。

      在不相关的注释中,您应该考虑通过const &amp; 传递对象,即:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-26
        • 1970-01-01
        • 2018-09-07
        相关资源
        最近更新 更多