2014-02-24 147 views
0

内单独.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); 

我的问题是,如果有,我叫DaTime一个干净的方式在Appt里面的构造函数?我知道这种方式是行不通的,因为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&) 

回答

2

aAppt数据成员并在构造函数初始化列表初始化:

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

而且,目前尚不清楚是否要按价值传递所有参数。考虑改为传递const引用。

注意:你所得到的错误似乎表明,你在你的类DaTime数据成员,你是不是构造函数初始化列表初始化。这意味着必须执行默认初始化,并且由于DaTime没有默认构造函数,因此会出现错误。记住:一旦你在构造函数的主体中,所有的数据成员都已经初始化。如果你没有明确地初始化它们,它们将被默认构建。

DaTime whenwhere; // I thought this would initialize it 

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

DaTime whenwhere{arg1, arg2, aer3}; 
+0

但是,我将不得不返回'a'? –

+0

@AllenS Ehm,no。 – juanchopanza

+0

是的,我确实有DaTime数据成员,所以这是有道理的。我以为我已经初始化了它。我讨厌发布大量的代码,但我会添加一个编辑来显示该部分的类。 –

0

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的值传递给Appt的构造函数,并创建一个DaTime的对象作为a= new DaTime(a,b,c)

或者是通过引用传递对象。

希望这会帮助你。

+0

感谢您的帮助。它并不能解决我的错误,尽管与我在解决方案上的尝试相比,它是有意义的。我做了一个编辑,以包含我的错误,因为可能我的错误在其他地方。 –

+0

@AllenS我的解决方案修复了这个错误。我会添加一个注释来解释原因。 – juanchopanza

相关问题