C++ static关键字:

本文详细介绍了C++中static关键字的使用方法及其特性。通过具体的代码示例,展示了如何利用static关键字来实现类成员的共享机制,并解释了静态成员与普通成员的区别。此外,还提供了一个包含静态成员变量和函数的类的实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Static的使用

(1).关键字static 可以用于说明一个类的成员;
静态成员提供了一个供所有对象共享机制;
(2).把一个类成员说明为static时,这个类无论有多少个对象被创建,这些对象共享这个static成员;
(3).静态成员局部于类,它不是对象成员
(4).类内的静态成员需要初始化。初始化方式:(例:在myclass中的静态成员 static int staticnum;
int myclass::staticnum=0;

2.static 使用demo

<constmutable.cpp>
#include "constmutable.h"
#include <iostream>
#include <stdio.h>
constmutable::constmutable(void): a(0),b(0),c(0),d(0)
{
    if (num>2)
    {
    }
    else
    {
        num++;
    }
}
int constmutable::num=0;
void constmutable::run()
{
    std::cout<<"This is run function!!"<<std::endl;
}
void constmutable::test()
{
    std::cout<<"This is test function!"<<std::endl;
}
constmutable::~constmutable(void)
{
}
<constmutable.h>
#pragma once
class constmutable{
public:
    constmutable();
    ~constmutable();
    int a;
    int b;
    int c;
    static int num;
    const int d;
    mutable int e;
public:
    static void run();
    void test();
    void setabc(int a,int b,int c )
    {
        this->a=a;
        this->b=b;
        this->c=c;
    }
    void showabc() const
    {
        this->e=1;
    }

};
main.cpp
#include "constmutable.h"
#include <iostream>
void main()
{
    constmutable num1;
    std::cout<<num1.num<<std::endl;
    constmutable num2;
    std::cout<<num2.num<<std::endl;
    constmutable::run();
    std::cin.get();
}

输出结果:

1
2
This is run function!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值