C++構(gòu)造函數(shù)的初始化列表詳解
1.問題
class A {
private:
int m_a;
public:
A(int a) {
cout << "A(int a)......." << endl;
m_a = a;
}
void print() {
cout <<"m_a=" << m_a << endl;
}
};
class B {
private:
int m_b;
A m_a1;
A m_a2;
public:
B(A& a1,A& a2, int b)
{
m_b = b;
m_a1(a1);//此處調(diào)用A的拷貝函數(shù)會報錯
m_a2(a2);//此處調(diào)用A的拷貝函數(shù)會報錯
}
};
錯誤:


2.解決方法(初始化列表)
將class B構(gòu)造函數(shù)改寫為:
public:
B(A& a1,A& a2, int b) :m_a1(a1),m_a2(a2)//構(gòu)造函數(shù)的初始化列表
{
m_b = b;
}
};
完整代碼如下:
#include <iostream>
using namespace std;
class A {
private:
int m_a;
public:
A(int a) {
cout << "A(int a)......." << endl;
m_a = a;
}
void print() {
cout <<"m_a=" << m_a << endl;
}
A(const A& another) {
m_a = another.m_a;
}
~A() {
cout << "~A()......" << endl;
}
};
class B {
private:
int m_b;
A m_a1;
A m_a2;
public:
B(A& a1,A& a2, int b) :m_a1(a1),m_a2(a2)//構(gòu)造函數(shù)的初始化列表,調(diào)用拷貝構(gòu)造
{
cout << "B(A& a1,A& a2, int b)......." << endl;
m_b = b;
}
~B() {
cout << "~B()......." << endl;
cout << "m_b=" << m_b << endl;
cout << "A m_a1" << endl;
m_a1.print();
cout << "A m_a2" << endl;
m_a2.print();
}
};
int main(int argc, char** argv) {
A a1(1), a2(2);
B b1(a1, a1, 3);
}
運行結(jié)果:

3.順序問題
構(gòu)造對象成員的順序跟初始化列表的順序無關(guān),而是跟成員對象定義的順序有關(guān)。(面試會問)
例子:
class A {
private:
int m_a;
public:
A(int a) {
cout << "A(int a)......." <<a<< endl;
m_a = a;
}
void print() {
cout <<"m_a=" << m_a << endl;
}
A(const A& another) {
m_a = another.m_a;
}
~A() {
cout << "~A()......"<< endl;
}
};
class B {
private:
int m_b;
A m_a2;
A m_a1;
public:
B(int a1, int a2, int b) :m_a1(a1), m_a2(a2)//調(diào)用有參構(gòu)造函數(shù)
{
cout << "B(int a1, int a2, int b)......." << endl;
m_b = b;
}
~B() {
cout << "~B()......." << endl;
}
};
int main(int argc, char** argv) {
B b2(1, 2, 3);
}
結(jié)果:

跟下面順序有關(guān):
private: A m_a2; A m_a1;
跟下面順序無關(guān):
B(int a1, int a2, int b) :m_a1(a1), m_a2(a2)//調(diào)用有參構(gòu)造函數(shù)
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
QT中QDataStream二進(jìn)制數(shù)據(jù)讀寫的實現(xiàn)
本文主要介紹了QT中QDataStream二進(jìn)制數(shù)據(jù)讀寫的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
詳解如何在code block創(chuàng)建一個C語言的項目
這篇文章主要介紹了詳解如何在code block創(chuàng)建一個C語言的項目,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
C++中幾種將整數(shù)轉(zhuǎn)換成二進(jìn)制輸出的方法總結(jié)
下面小編就為大家?guī)硪黄狢++中幾種將整數(shù)轉(zhuǎn)換成二進(jìn)制輸出的方法總結(jié)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-09-09
C++實現(xiàn)leetcode(3.最長無重復(fù)字符的子串)
這篇文章主要介紹了C++實現(xiàn)leetcode(3.最長無重復(fù)字符的子串),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
C++在成員函數(shù)中使用STL的find_if函數(shù)實例
這篇文章主要介紹了C++在成員函數(shù)中使用STL的find_if函數(shù)實例,包括了STL中find_if函數(shù)的具體用法及相關(guān)的完整實例,非常具有參考借鑒價值,需要的朋友可以參考下2014-10-10
詳解C++虛函數(shù)中多態(tài)性的實現(xiàn)原理
C++是一種面向?qū)ο蟮木幊陶Z言,在C++中,虛函數(shù)是實現(xiàn)多態(tài)性的關(guān)鍵。本文就來探討一下C++虛函數(shù)中多態(tài)性的實現(xiàn)原理及其在面向?qū)ο缶幊讨械膽?yīng)用吧2023-05-05

