[英]Constructor with an object as argument (C++)
I have this class:我有这个 class:
class CContact {
public:
CTimeStamp m_Stamp;
int m_Num1;
int m_Num2;
CContact(CTimeStamp mStamp, int i, int i1) {
m_Stamp = mStamp;
m_Num1 = i;
m_Num2 = i1;
}
};
I get the following error:我收到以下错误:
Constructor for 'CContact' must explicitly initialize the member 'm_Stamp' which does not have a default constructor
“CContact”的构造函数必须显式初始化没有默认构造函数的成员“m_Stamp”
I want to be able to use it this way:我希望能够以这种方式使用它:
test.addContact(CContact(CTimeStamp(1, 2, 3, 4, 5, 6), 999999999, 777777777));
What does it mean, and how can I fix it?这是什么意思,我该如何解决?
The error is self-explantory.该错误是不言自明的。 Your
CContact
constructor is not passing any values to m_Stamp
's constructor, so the compiler has to default-construct m_Stamp
, but it can't because CTimeStamp
does not have a default constructor .您的
CContact
构造函数没有将任何值传递给m_Stamp
的构造函数,因此编译器必须默认构造m_Stamp
,但不能因为CTimeStamp
没有 默认构造函数。
You need to initialize CContact
's members (or at least m_Stamp
) in the CContact
constructor's member initialization list rather than in the constructor's body, eg:您需要在
CContact
构造函数的成员初始化列表中而不是在构造函数的主体中初始化CContact
的成员(或至少m_Stamp
),例如:
CContact(CTimeStamp mStamp, int i, int i1) :
m_Stamp(mStamp),
m_Num1(i),
m_Num2(i1)
{
}
This will invoke the copy constructor for m_Stamp
rather than the default constructor.这将调用
m_Stamp
的复制构造函数,而不是默认构造函数。
You original code was effective equivalent to this, which is why it failed:您的原始代码与此等效,这就是它失败的原因:
CContact(CTimeStamp mStamp, int i, int i1)
: m_Stamp() // <-- here
{
m_Stamp = mStamp;
m_Num1 = i;
m_Num2 = i1;
}
You have to define a default constructor for class CTimeStamp
.您必须为 class
CTimeStamp
定义一个默认构造函数。 For example:例如:
CTimeStamp(int aa=0, int bb=0, int cc=0)
:a{aa},b{bb},c{cc}{}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.