وفي 19/شوال/1429 09:18 ص، أعرب وسام البهنسي عن رأيه بالموقف كالآتي:
* تهيئة المتغيرات تتم في الـ initializer list في الـ constructor، بدلاً من جسم الـ constructor نفسه... مثلاً:class Explorer
{
private:
int m_iMemberOne;
float m_fMemberTwo;
Explorer()
{
m_iMemberOne = 0;
m_fMemberTwo = 0.0f;
}
};
class Explorer
{
private:
int m_iMemberOne;
float m_fMemberTwo;
Explorer() :
m_iMemberOne(0),
m_fMemberTwo(0.0f)
{
}
};
#include
class MemberClass
{
public:
MemberClass()
// Initialize internal variables here
{
std::cout << "MEMBERCLASS: Default constructor called" << std::endl;
}
MemberClass(const MemberClass& rhs)
// Initialize internal variables here
{
std::cout << "MEMBERCLASS: Copy-Constructor called" << std::endl;
}
~MemberClass()
{
std::cout << "MEMBERCLASS: Destructor called" << std::endl;
}
const MemberClass& operator =(const MemberClass& op)
{
// Assign internal variables here
std::cout << "MEMBERCLASS: Assignment operator called" << std::endl;
return *this;
}
};
class InitListTest
{
public:
InitListTest(const MemberClass &init)
:m_Internal(init)
{ }
protected:
MemberClass m_Internal;
};
class AssignTest
{
public:
AssignTest(const MemberClass &init)
{ m_Internal = init;}
protected:
MemberClass m_Internal;
};
int main()
{
std::cout << "Create local copy of MemberClass" << std::endl;
MemberClass local;
std::cout << "Begin test:" << std::endl;
std::cout << "Initializer list" << std::endl;
InitListTest testInitList(local);
std::cout << "Simple Assignment" << std::endl;
AssignTest testAssign(local);
std::cout << "---End test" << std::endl;
}
Create local copy of MemberClass
MEMBERCLASS: Default constructor called
Begin test:
Initializer list
MEMBERCLASS: Copy-Constructor called
Simple Assignment
MEMBERCLASS: Default constructor called
MEMBERCLASS: Assignment operator called
---End test
MEMBERCLASS: Destructor called
MEMBERCLASS: Destructor called
MEMBERCLASS: Destructor called
Press any key to continue . . .
// الكلاس الأب
class Parent
{
public:
Parent(const char* Name)
{
std::cout << Name << std::endl; // اطبع البارامتر
}
};
// الكلاس الابن
class Child : public Parent
{
public:
Child() : Parent("I am a child") // نادي الباني بتاع الأب، ومررله أي حاجة
{
}
};