c++ - 当我在函数中定义时,cpp 组合中没有定义
问题描述
#include <iostream>
using namespace std;
class Date{
private:
int day;
int month;
int year;
public:
Date(int dy,int mt,int yr){
day=dy;
month=mt;
year=yr;
}
void showDate(){
cout<<day<<"/"<<month<<"/"<<year<<endl;
}
};
class Human{
private:
string name;
Date birthDay;
public:
Human(string nm,Date bd):name(nm),birthDay(bd){};
showHumanInfo(){
cout<<"The person named : "<<name<<" was born : ";
birthDay.showDate();
}
};
int main()
{
Date birthday(1,2,1995);
Human h1("alek",birthday);
h1.showHumanInfo();
return 0;
}
这行得通,但是为什么当我执行以下操作时它不起作用?
#include <iostream>
using namespace std;
class Date{
private:
int day;
int month;
int year;
public:
Date(int dy,int mt,int yr){
day=dy;
month=mt;
year=yr;
}
void showDate(){
cout<<day<<"/"<<month<<"/"<<year<<endl;
}
};
class Human{
private:
string name;
Date birthDay;
public:
Human(string nm,Date bd){
name = nm;
birthDay = bd;
}
showHumanInfo(){
cout<<"The person named : "<<name<<" was born : ";
birthDay.showDate();
}
};
int main()
{
Date birthday(1,2,1995);
Human h1("alek",birthday);
h1.showHumanInfo();
return 0;
}
我有这样的问题。为什么我不能在人类课程中使用日期课程?
当我像那样改变人类公共课时
public:
human(){
// ...
}
它不起作用是一样的想法,但没有在人类课程中添加日期课程。
解决方案
在构造函数的定义中,所有的成员变量都必须在构造函数体执行之前进行初始化。由于Date
没有默认构造函数,因此无法对其进行初始化
Human(string nm, Date bd)
{ // birthDay must be initialized before this point
// ...
birthDay = bd; // this is assignment, which is too late
}
修复方法是提供Date
默认构造函数(如果有意义),或者birthDay
在成员初始化程序列表中进行初始化,就像您在第一个示例代码中所做的那样。
推荐阅读
- apache-poi - POI 4.1.1 setCellFormula 未显示最终值
- r - 如何绘制具有 3 个变量的条形图?
- r - 有没有使用条件过滤和删除单个行的好方法?
- r - 计算 1 df 中的坐标向量与其他 df 中的单个坐标之间的距离
- php - Laravel:仅获取特定路由的属性访问器
- serverless-framework - 在 lambda@edge 上使用Sharp
- python - Fractional Max-Pooling:我发现难以实现的深度神经网络
- android - 如何解决返回 null 的 DefaultTrackSelector#getCurrentMappedTrackInfo?
- iframe - 防止在 iframe 中单击鼠标右键
- javascript - 量角器不断耗尽内存