在构造函数中调用不同类的构造函数?
Calling different class' constructor in a constructor?
在单独的.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)
。
或者通过引用传递对象。
希望这对您有所帮助。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 不同类的构造函数的重载解析
- 在构造函数中调用不同类的构造函数?
- 具有两个不同类的两个不同构造函数
- 如何在C++中的不同类main中传递类的构造函数参数
- 从不同类的构造函数调用构造函数
- 如何在不同类的构造函数中使用模板化类