面向对象的编程——成员变量赋值(2)

来源:互联网 发布:spark sql 例子 编辑:程序博客网 时间:2024/05/18 03:30

面向对象的编程——成员变量赋值(2)

#include <iostream>

#include <string>

using namespace std;

 

class test

{

private:

         int t1;

         int t2;

public:

         test():t2(0),t1(t2) {}

         test(int i):t2(i),t1(t2) {}

         int get1()

         {

                   return t1;

         }

         int get2()

         {

                   return t2;

         }

};

 

int main()

{

         test t(10);

         cout<<t.get1()<<endl<<t.get2()<<endl;

return 0;

}

上述程序运行结果:

而不是10和10,那是因为在初始化列表的初始化变量顺序是按照成员变量的申明顺序来的,所以上面应当先用t2初始化t1,t2由于没有初始化,故t1是个随机数。

修改如下:

运行结果如下:

题外话:

为什么把最后打印输出语句改成“cout<<t.get1<<endl<<t.get2<<endl;”之后结果就是1,1?