C++之类的静态成员函数和静态成员变量

C++之类的静态成员函数和静态成员变量

静态成员在类的所有对象中是共享的。即只要在类外初始化之后,该类的所有对象都可以对静态成员进行操作。静态成员变量只能在类内声明,在类外定义,静态成员函数不能调用非静态成员函数,但是可以调用全局函数。

#include <iostream>

using namespace std;

class TClass {
public:
    //错误写法,static int b =2;静态成员变量只能在类外定义,类内声明,通过int TClass::b = 2;
    //注意int TClass::b =2;不要放在函数内部。需要在全局定义。
    static int b;

    void printf_function() { ; }

    static int get_b() { return b; };

    static int get_c() { return c; }

    //错误写法,静态成员函数不能调用非静态成员函数
    /**static void error_function() {
        printf_function();
    }**/
    static void use_local_function();

    static int use_another();

private:
    static int c;
};

void locale_function();

int TClass::b = 2;
int TClass::c = 3;

void TClass::use_local_function() {
    locale_function();
}

int TClass::use_another() {
    locale_function();
    return 1;
}

int main() {
    system("chcp 65001");
    TClass tClass;
    cout << "tClass对象调用静态成员变量b的值:" << tClass.get_b() << endl;
    cout << "tClass对象调用私有静态成员变量c的值:" << tClass.get_c() << endl;
    //无返回值的全局函数
    TClass::use_local_function();
    //cout流不能输出无返回值的函数
    cout << tClass.use_another() << endl;
    return 0;
}

void locale_function() {
    printf("静态成员函数调用全局函数\n");
}
输出:
Active code page: 65001
tClass对象调用静态成员变量b的值:2
tClass对象调用私有静态成员变量c的值:3
静态成员函数调用全局函数
静态成员函数调用全局函数
1
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值