在构造函数中调用不同类的构造函数?

Calling different class' constructor in a constructor?

本文关键字:构造函数 同类 调用      更新时间:2023-10-16

在单独的.h文件中:

    class Appt{
        public:
        Appt(string location, string individual, DaTime whenwhere);
        private:
        string individual;
        string location;
        DaTime whenwhere;  // I thought this would initialize it 
        DaTime a;
    }
    class DaTime{
        public:
        DaTime(Day day, Time start, Time end); // Day is enum, Time is class
        private:
        int duration;
        Day day;
        Time start;
        Time end; 
    }

在单独的.cc文件中:

    // class Appt constructor
    Appt::Appt(string location, string individual, DaTime whenwhere)
    {
            a_SetLocation(location);
            a_SetIndividual(individual);
            DaTime a(whenwhere); // THE LINE IN QUESTION
    }
    // class DaTime constructor
    DaTime::DaTime(Day day, Time start, Time end)
    {
            dt_SetDay(day);
            dt_SetStart(start);
            dt_SetEnd(end);
    }

内部main()

    /* Creating random variables for use in our classes */
    string loc1 = "B";
    string p1 = "A";
    /* Creating instances of our classes */
    Time t1(8, 5), t2(8, 30);
    DaTime dt1('m', t1, t2);
    Appt A1(loc1, p1, dt1);

我的问题是是否有一种干净的方法让我在Appt内部调用DaTime构造函数?我知道这种方式是行不通的,因为我的DaTime实例,a会在constructor完成后死亡。

编辑:我得到的错误是:

    In constructor ‘Appt::Appt(std::string, std::string, DaTime)’:
    appt.cc: error: no matching function for call to ‘DaTime::DaTime()’
     Appt::Appt(string location, string individual, DaTime when where)
    In file included from appt.h:15:0,
             from appt.cc:15:
    class.h:note: DaTime::DaTime(Day, Time, Time)
      DaTime(Day day, Time start, Time end);
      ^
    note:   candidate expects 3 arguments, 0 provided
    note: DaTime::DaTime(const DaTime&)

使a成为Appt的数据成员,并在构造函数初始化列表中对其进行初始化:

Appt::Appt(string location, string individual, DaTime whenwhere) : a (whenwhere)
{
  ....
}

此外,不清楚是否要按值传递所有参数。请考虑改为传递const引用。

注意:您收到的错误似乎表明您的类中确实有一个 DaTime 数据成员,并且您没有在构造函数初始化列表中初始化它。这意味着必须执行默认初始化,并且由于DaTime没有默认构造函数,因此会出现错误。请记住:一旦你进入构造函数的主体,你的所有数据成员都已经初始化了。如果不显式初始化它们,则会默认构造它们。

DaTime whenwhere;  // I thought this would initialize it 

这不是初始化。它只是一个成员声明。 whenwhere将在调用DaTime构造函数时初始化。在 C++11 中,您还可以在声明点初始化:

DaTime whenwhere{arg1, arg2, aer3};

在类Appt中包括以下代码:

DaTime a;

Appt的构造函数

Appt::Appt(string location, string individual, DaTime whenwhere)
    {
            a_SetLocation(location);
            a_SetIndividual(individual);
            a = whenwhere; //call copy constructor of `DaTime`
    }

关于错误:

您的 DaTime 类没有默认构造函数。

因此,您可以做的是传递 DaTime 的值 ti 的构造函数 Appt 并创建一个 DaTime 对象作为 a= new DaTime(a,b,c)

或者通过引用传递对象。

希望这对您有所帮助。