In the process of programming with C + +, it is often necessary to initialize class members in two ways:
The first method:
CMYClass::CSomeClass()
{
x=0;
y=1;
}
The second method:
CSomeClass::CSomeClass() : x(0), y(1)
{
}
This paper will explore the similarities and differences between the two methods and how to use them.
Technically, the second approach is better, but in most cases there is no difference between the two. The second syntax is called the member initialization list, and there are two reasons to use this syntax: One reason is that you have to do this, and the other reason for efficiency considerations.
Let's first look at the first reason-necessity. Imagine that you have a class member, which is itself a class or struct, and has only one constructor with one parameter.
class CMember {
public:
CMember(int x) { ... }
};
Because Cmember has an explicitly declared constructor, the compiler does not produce a default constructor (without arguments), so there is no integer that cannot create an instance of Cmember.
CMember* pm = new CMember; // 出错!!
CMember* pm = new CMember(2); // OK
If Cmember is a member of another class, how do you initialize it? The answer is that you have to use the member initialization list.
class CMyClass {
CMember m_member;
public:
CMyClass();
};
// 必须使用初始化列表来初始化成员 m_member
CMyClass::CMyClass() : m_member(2)
{
•••
}
There is no other way to pass parameters to M_member, if the member is a constant object or the reference is the same. Depending on the rules of C + +, constant objects and references cannot be assigned, they can only be initialized.
The second reason to use the initialization list is because of efficiency considerations when the member class has a default constructor and an assignment operator. The CString of MFC provides a perfect example. Suppose you have a class CMyClass with a CString type of member M_STR, you want to initialize it to "hi,how are you." You have two options:
CMyClass::CMyClass() {
// 使用赋值操作符
// CString::operator=(LPCTSTR);
m_str = _T("Hi,how are you.");
}
// 使用初始化列表
// 和构造函数 CString::CString(LPCTSTR)
CMyClass::CMyClass() : m_str(_T("Hi,how are you."))
{
}