C++中多个参数的初始化顺序问题
决定参数初始化顺序的因素
1.跟参数列表的初始化顺序无关
2.取决于声明对象的顺序
实例
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<new>
using namespace std;
class A
{
public:
A(int x) :m_x(x)
{
cout << "A::A(int)" << endl;
}
private:
int m_x;
};
class B
{
public:
B(int y) :m_y(y)
{
cout << "B::B(int)" << endl;
}
private:
int m_y;
};
class C
{
public:
C(int z) :m_z(z)
{
cout << "C::C(int)" << endl;
}
private:
int m_z;
};
class Test
{
public:
Test(int a, int b, int c) :m_a(a), m_b(b), m_c(c)
{}
private:
A m_a;
B m_b;
C m_c;
};
int main()
{
Test t(10, 20, 30);
}
更改参数列表初始化顺序
class Test
{
public:
Test(int a, int b, int c) : m_c(c) ,m_b(b),m_a(a)
{}
private:
A m_a;
B m_b;
C m_c;
};
int main()
{
Test t(10, 20, 30);
system("pause");
}
更改声明顺序
class Test
{
public:
Test(int a, int b, int c) :m_a(a), m_b(b), m_c(c)
{}
private:
B m_b;
C m_c;
A m_a;
};
int main()
{
Test t(10, 20, 30);
system("pause");
}