8、static用法

/*
 * 静态成员 属于类成员,不属于任何一个对象,所有对象共享静态成员变量
 *
 *1、静态成员函数s_print(),定义的时候不能函数前不能加static
 *2、静态成员变量初始化时,必须加上const,不然报错 
 *3、静态成员函数无this 指针,因此不能调用非静态成员函数/变量
 *4、非静态成员函数可以直接调用静态成员变量,而不用通过类作用域
 *
 *5、
 * */


#include <iostream>

using namespace std;

class myTest
{
    public:
        static void s_print();
        void print();

        static int c;
    private:
        //int a;              // 只有static 静态成员才需要在外面定义
        int a = 1;
        static int b;
        const static int d = 10;    // 类内初始化static必须加const 或者constexpr
        static constexpr int e = 20; 
};

void myTest::print()
{
    cout << "print " << "a = " << a <<endl;
    cout << "print " << "b = " << b <<endl;
}

void myTest::s_print()
{
    myTest t1; 
    t1.a = 100;
    t1.b = 200;
    cout << "s_print " << "a = " << t1.a <<endl;  // 可以这样调用非静态成员变量,但不能用this指针隐式或显示的调用
    cout << "s_print " << "b = " << b <<endl;
}

//myTest g_t;
//g_t.c = 10;

// 此处应当定义,不然报错未定义的 myTest::c ,定义前面不加 static
//int myTest::c = 20;
int myTest::c;
int myTest::b = 300;

int main(int argc, const char *argv[])
{
    myTest t;
    myTest t2;

    t.print();
    t2.s_print();

    cout << ".....\n";
    t.print();
    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值