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

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.lqws.cn/news/213211.html

相关文章:

  • 《高精度》题集
  • 【题解-洛谷】B3622 枚举子集(递归实现指数型枚举)
  • 【Latex】Windows/Ubuntu 绘制 eps 矢量图通用方法(drawio),支持插入 Latex 数学公式
  • 一款“短小精悍的”手机录屏软件
  • 安达发|装饰材料行业APS生产排程软件:破解生产困局,智造升级新引擎
  • Java高级 |【实验八】springboot 使用Websocket
  • Spring中循环依赖问题的解决机制总结
  • day 27 装饰器函数
  • [GitHub] 优秀开源项目
  • 区块链技术概述
  • Java方法引用深度解析:从匿名内部类到函数式编程的演进
  • MySQL 8.0 绿色版安装和配置过程
  • SQL Server 日期时间类型全解析:从精确存储到灵活转换
  • SpringBoot十二、SpringBoot系列web篇之过滤器Filte详解
  • 使用Caddy在Ubuntu 22.04上配置HTTPS反向代理
  • 开疆智能Ethernet/IP转Modbus网关连接鸣志步进电机驱动器配置案例
  • 指针的定义与使用
  • Python 接口:从协议到抽象基 类(定义并使用一个抽象基类)
  • 虚幻引擎5-Unreal Engine笔记之SET节点的输出引脚获取设置后的最新变量值
  • 露亦如电 · 时之沙 | 让遗憾在灰烬里随风而去
  • CCPC chongqing 2025 L
  • Faiss向量数据库全面解析:从原理到实战
  • 5.4.2 Spring Boot整合Redis
  • 汇编语言学习(三)——DoxBox中debug的使用
  • 从代码学习深度强化学习 - 初探强化学习 PyTorch版
  • [学习] GNSS信号跟踪环路原理、设计与仿真(仿真代码)
  • RTOS学习之重难点
  • 关于GitHub action云编译openwrt
  • 应急响应思路
  • 大故障,阿里云核心域名疑似被劫持