初始化清單
#include<iostream>
//初始化清單
using namespace std;
class Person
{
public:
Person(int a,int b,int c):m_A(a),m_B(b),m_C(c)
{
}
int m_A;
int m_B;
int m_C;
};
void test01()
{
Person p(30,20,10);
cout << p.m_A << endl;
cout << p.m_B << endl;
cout << p.m_C << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
結果:
類對象作為類成員
#include<iostream>
#include<string.h>
//初始化清單
using namespace std;
class Phone
{
public:
Phone(string m_pname):p_name(m_pname)
{
// p_name = m_pname;
}
Phone(int m_number) :p_number(m_number)
{
}
string p_name;
int p_number;
};
class Person
{
public:
Person(string name, string p_name,int num):m_name(name),m_phone(p_name),m_number(num)
{
}
string m_name;
Phone m_phone;
Phone m_number;
};
void test01()
{
Person p("iphone","iphone12",11111);
cout << "手機;" << p.m_name << endl;
cout << "型号;" << p.m_phone.p_name << endl;
cout << "号碼;" << p.m_number.p_number<< endl;
}
int main()
{
test01();
system("pause");
return 0;
}
在person和phone類運作時到底是誰先運作,誰後運作呢?
我們來探讨探讨。
#include<iostream>
#include<string.h>
//初始化清單
using namespace std;
class Phone
{
public:
Phone(string m_pname):p_name(m_pname)
{
cout << "Phone name構造函數運作" << endl;
}
Phone(int m_number) :p_number(m_number)
{
cout << "Phone Number構造函數運作" << endl;
}
string p_name;
int p_number;
};
class Person
{
public:
Person(string name, string p_name,int num):m_name(name),m_phone(p_name),m_number(num)
{
cout << "Person構造函數運作" << endl;
}
string m_name;
Phone m_phone;
Phone m_number;
};
void test01()
{
Person p("iphone","iphone12",11111);
cout << "手機;" << p.m_name << endl;
cout << "型号;" << p.m_phone.p_name << endl;
cout << "号碼;" << p.m_number.p_number<< endl;
}
int main()
{
test01();
system("pause");
return 0;
}
構造順序:
當其他類對象作為本類成員,構造時候先構造對象,再構造自身。
析構順序與構造相反。