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

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.lryc.cn/news/2404853.html

相关文章:

  • 分布式爬虫代理IP使用技巧
  • 数据分析之OLTP vs OLAP
  • Flask音频处理:构建高效的Web音频应用指南
  • powershell 安装 .netframework3.5
  • dvwa5——File Upload
  • cv::FileStorage用法
  • Go 语言 := 运算符详解(短变量声明)
  • 【优选算法】C++滑动窗口
  • 关于GitHub action云编译openwrt
  • 数据库学习(二)——MySQL语句
  • AI Agent 架构设计:ReAct 与 Self-Ask 模式对比与分析
  • sql入门语句-案例
  • A Survey on the Memory Mechanism of Large Language Model based Agents
  • 华为OD机试 - 猴子吃桃 - 二分查找(Java 2025 B卷 200分)
  • 提取数据区域中表格
  • 【设计模式-5】设计模式的总结
  • 【无人机】无人机UAV、穿越机FPV的概念介绍,机型与工具,证书与规定
  • 链表好题-多种实现
  • oracle数据恢复—oracle数据库执行truncate命令后的怎么恢复数据?
  • OneNet + openssl + MTLL
  • 分享两个日常办公软件:uTools、PixPin
  • Golang基础学习
  • [学习] GNSS信号跟踪环路原理、设计与仿真(仿真代码)
  • Python实例题:Python计算微积分
  • 如何判断指针是否需要释放?
  • Spark 之 AQE
  • 随访系统安装的记录
  • NLP学习路线图(二十四):门控循环单元(GRU)
  • Doris查询Hive数据:实现高效跨数据源分析的实践指南
  • vsCode使用本地低版本node启动配置文件