私有静态成员变量的注意事项

私有静态成员变量的注意事项

1.首先,静态成员变量的作用是什么?

	作用:为了同一个类的所有对象之间能够“共享”数据。

2.那私有的静态成员变量又是咋回事呢?

 private修饰的静态成员变量只能在类内访问,但也必须在类外初始化,
 并且只能通过成员函数进行访问。

注意:const修饰的静态成员变量只能在类内初始化。并且只能为public属性。

public:
const static int num_1 = 4;
protected:
    //const static int num_2 = 4;   error
private:
    //const static int num_3 = 4;   error

完整测试代码如下:

#include <iostream>
using namespace std;

class test
{
public:
    test(void)
    {
        cout << "hello" << endl;
    };
    ~test(){};
    void vout_num_0()
    {
        cout << num_0 << endl;
    };
private:
    static int num_0;
    //const static int num_2 = 4;   error
protected:
    //const static int num_3 = 4;   error
public:
    static int num_1;
    const static int num_2 = 4;
};
int test::num_0 = 1;
int test::num_1 = 2;

int main ()
{
    test *mtest = NULL;
    test ntest;
    mtest->num_1 = 3;
    ntest.num_1 = 4;
    mtest->vout_num_0();
    ntest.vout_num_0();
    //cout << mtest->num_0 << endl;   error
    //cout << ntest.num_0 << endl;    error
    cout << mtest->num_1 << endl;
    cout << ntest.num_1 << endl;
    cout << ntest.num_2 << endl;
    return 0;
}

测试结果如下:

[Running] cd "c:\Users\Lenovo\Documents\" && g++ test.cpp -o test && "c:\Users\Lenovo\Documents\"test
hello
1
1
4
4
4
[Done] exited with code=0 in 0.353 seconds
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值