首页 > 解决方案 > 当我在函数中定义时,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(){
 //  ...
}

它不起作用是一样的想法,但没有在人类课程中添加日期课程。

标签: c++composition

解决方案


在构造函数的定义中,所有的成员变量都必须在构造函数体执行之前进行初始化。由于Date没有默认构造函数,因此无法对其进行初始化

Human(string nm, Date bd)
{  // birthDay must be initialized before this point
   // ...
   birthDay = bd; // this is assignment, which is too late
}

修复方法是提供Date默认构造函数(如果有意义),或者birthDay在成员初始化程序列表中进行初始化,就像您在第一个示例代码中所做的那样。


推荐阅读