当前位置: 首页 > web >正文

c++ 静态成员变量

Student.h头文件内容:

#pragma once
#include <string>
using namespace std;class Student
{
public:string name;int score;static int totalScore; // 静态局部变量声明Student(string name, int score);~Student();void print() const;
};

Student.cpp源文件内容:

#include "Student.h"
#include <iostream>Student::Student(string name, int score) : name(name), score(score) {Student::totalScore += score;
}int Student::totalScore = 0; // 静态成员变量定义和初始化, 必须Student::~Student() {cout << "student: " << name << " 析构" << endl;
}void Student::print() const {cout << "student: " << name << ", my score:" << score << " , all students' total score: " << Student::totalScore << endl;
}

测试代码:

#include "Student.h"void testStaticVal() {Student* stu1 = new Student("隔壁老王", 60);stu1->print();Student* stu2 = new Student("隔壁老宋", 80);stu2->print();delete stu1;delete stu2;std::cout << "totalScore: " << Student::totalScore << std::endl;
}

打印:

ok. 静态成员变量属于类,在全局数据区分配内存。

http://www.xdnf.cn/news/12749.html

相关文章:

  • JavaScript中的函数总结
  • 人工智能赋能高中学科教学的应用与前景研究
  • Macbook M3 使用 VMware Fusion 安装 openEuler24.03LTS
  • 言思集交流社区(SpringBoot)
  • leetcodeT3170
  • MIT 6.S081 Lab10 mmap
  • java报错ncapp生成主子表单据时报错,CarrierRuntimeException
  • 关于Qt阻断样式继承的解决办法
  • yolov12-区域注意力:让计算机“看见”更智能
  • Java 中 synchronized 和 ReentrantLock 的全面对比解析
  • ELK日志管理框架介绍
  • 在C语言中使用UUID作为AES加密密钥
  • python打卡第47天
  • 快速排序算法详解:从理论到实践的全方位指导
  • 从零开始制作小程序简单概述
  • JavaScript ES6 解构:优雅提取数据的艺术
  • 论文略读:Efficient Reasoning for LLMs through Speculative Chain-of-Thought
  • vue中的派发事件与广播事件,及广播事件应用于哪些场景和一个表单验证例子
  • Android 视图系统入门指南
  • C++常用的企业级日志库
  • 绘制饼图详细过程
  • qt使用笔记二:main.cpp详解
  • STM32的系统滴答定时器简述
  • fast-reid部署
  • LangChain面试内容整理-知识点1:LangChain架构与核心理念
  • 高并发下的缓存击穿/雪崩解决方案
  • 青少年编程与数学 01-011 系统软件简介 08 Windows操作系统
  • JavaWeb基础入门 — SpringBoot Web 案例详解
  • LBE-LEX系列工业语音播报器|AGV语音提示器|工程车音乐报警器操作使用说明
  • 亚川科技IBMS集成管理平台:构建商业综合体智慧中枢