美文网首页
C++ 中 static 关键字

C++ 中 static 关键字

作者: 红鲤鱼与绿鲤鱼与驴与鱼 | 来源:发表于2023-10-09 21:34 被阅读0次
/**
 C++ static 关键字
 静态: 先定义,后赋值(类内定义,类外赋值)
 */

#include <stdio.h>
#include <iostream>

using namespace std;

class Dog{
public:
    char* info;
    int age;
    
    //先定义,后赋值
    static int id;
    static void update(int a){
        id=a;
    }
    
    void update2(int a ){
        id = a;
    }
};

//赋值操作
int Dog::id = 10;

int main(){
    Dog dog;
    dog.update(13);
    cout<< dog.id << endl;
    return 0;
}

关于静态的总结:

  • 1、可以直接通过 类名::静态成员(字段/函数)
  • 2、静态的属性必须要初始化,然后再实现(在类内部初始化,外部实现)
  • 3、静态的函数只能操作静态的属性和方法(和Java一样)

相关文章

网友评论

      本文标题:C++ 中 static 关键字

      本文链接:https://www.haomeiwen.com/subject/yxxwbdtx.html