#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
class Obj
{
public:
Obj(int k) : j(k), i(j) {
}
void print(void)
{
cout << "i = " << i << " , j = " << j << endl;
}
private:
int i;
int j;
};
int main(int argc, char** argv)
{
Obj j(2);
j.print();
return 0;
}
输出:
i = 0 , j = 2
#说明 这里的 i 并没有等于 2 而是一个随机值.
修改 i 和 j 的位置, 如下:
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
class Obj
{
public:
Obj(int k) : j(k), i(j) {
}
void print(void)
{
cout << "i = " << i << " , j = " << j << endl;
}
private:
int j;
int i; //这里换了一下位置
};
int main(int argc, char** argv)
{
Obj j(2);
j.print();
return 0;
}
输出:
i = 2 , j = 2
#输出符合预期
#初始化列表的初始顺序与变量声明的顺序一致.