c++类中对数据成员进行初始化和赋值的区别

来源:互联网 发布:c语言d什么意思 编辑:程序博客网 时间:2024/06/06 12:53

在c++中定义一个类 ,对于构造函数 我们经常是这么写的:

class test{public:       test(int n_x , int n_y)    {        x = n_x;        y = n_y;    }private:    int x , y;};

这中写法虽然是合法的但比较草率

在构造函数 test(int n_x , int n_y)中 , 我们这样实际上不是对数据成员进行初始化 , 而是进行赋值。


正确的是初始化应该是这样的:

class test{public:    test()  {}    test(int n_x , int n_y):x(n_x) , y(y)  {}private:    int x , y;};


虽然大部分时候赋值和初始化是没有区别的 , 但是构造函数的初始化值有时必不可少,例如:

class test{public:    test()  {}    test(int n_x , int n_y , int z_x)    {        i = n_x;        ci = n_y;        ri = z_x;    }private:    int i;    const int ci;    int &ri;};

上面代码的红色部分就是错误的 , 因为const 和 引用类型的数据成员的唯一机会就是通过构造函数进行初始化值。

因此,正确形式:


test(int n_x , int n_y , int z_x):i(n_x) , ci(n_y) , ri(n_z)  {}



0 0
原创粉丝点击