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

时间:2014-05-14 20:13:39   收藏:0   阅读:322

在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)  {}



c++类中对数据成员进行初始化和赋值的区别,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!