c++ - 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)
{
}
};
解决方案
在 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) {
}
推荐阅读
- angular - 表单控件上的角度模式验证失败,直到您编辑该字段
- android - 如何通过传递参数从离子混合应用程序打开本机自己的android应用程序
- python - 如何修复 scipy 的 odeint 函数中的 np.float64 不可调用错误?
- r - Rcpp中两个稀疏矩阵的快速余弦相似度与犰狳
- r - 通过 R 中的函数安装自己的 R 包
- python - Python Pandas 只删除具有 NaN 值的两行之一
- python - Python Web-scraping,类别提取
- python - 我如何避免在 linux 上的 chromium 中检测硒?
- c++ - ':' - 类构造函数中的运算符
- spring-integration - 如何暂停Spring云数据流Source类向kafka发送数据?