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

C++中static关键字的用法(实现日期类)

1.先看概念

静态static_百度百科

static 关键字在 C++ 中有多种用法,主要用于控制变量的存储期和作用域。理解 static 的用法有助于更好地管理内存和程序结构。

2.静态变量

2.1局部静态变量

局部静态变量在函数内部声明,生命周期是整个程序运行期间,但作用域仅限于该函数。

#include <iostream>
using namespace std;

void function() {
    static int count = 0; // 只初始化一次
    count++;
    cout << "Count: " << count << endl;
}

int main() {
    for (int i = 0; i < 5; i++) {
        function();
    }
    return 0;
}

2.2全局静态变量

全局静态变量在文件作用域内声明,其他文件无法访问。

#include <iostream>
using namespace std;

static int globalVar = 10; // 仅在此文件可见

void display() {
    cout << "Global Variable: " << globalVar << endl;
}

int main() {
    display();
    return 0;
}

3.静态成员变量

静态成员变量属于类,而不是类的某个对象。它们在所有对象之间共享。

#include <iostream>
using namespace std;

class MyClass {
public:
    static int count; // 声明静态成员变量

    MyClass() {
        count++;
    }
};

// 定义静态成员变量
int MyClass::count = 0;

int main() {
    MyClass obj1;
    MyClass obj2;
    cout << "Count of objects: " << MyClass::count << endl; // 输出: 2
    return 0;
}

4.静态成员函数

静态成员函数可以访问静态成员变量,但不能访问非静态成员变量和函数。

#include <iostream>
using namespace std;

class MyClass {
public:
    static int count; // 静态成员变量

    static void displayCount() {
        cout << "Count: " << count << endl;
    }
};

int MyClass::count = 5;

int main() {
    MyClass::displayCount(); // 输出: Count: 5
    return 0;
}

5.静态访问

使用 static 声明的全局变量和函数只在声明它们的文件中可见,这称为静态链接。可以防止名称冲突。

// file1.cpp
#include <iostream>
using namespace std;

static void staticFunction() {
    cout << "This is a static function in file1." << endl;
}

// file2.cpp
#include <iostream>
using namespace std;

// staticFunction() 在此文件不可见

int main() {
    // staticFunction(); // 会报错
    return 0;
}

6.用static实现日期类

6.1静态方法的使用

在上述代码中,我们定义了两个静态方法:

  • getCurrentDate()返回一个固定的当前日期。

  • isLeapYear(int year)判断给定年份是否为闰年。

6.2日期类的定义

  • #include <iostream>
    #include <string>
    
    class Date {
    private:
        int day;
        int month;
        int year;
    
    public:
        // 构造函数
        Date(int d, int m, int y) : day(d), month(m), year(y) {}
    
        // 获取日期字符串
        std::string getDateString() const {
            return std::to_string(day) + "/" + std::to_string(month) + "/" + std::to_string(year);
        }
    
        // 静态方法: 获取当前日期(假设为固定日期)
        static Date getCurrentDate() {
            return Date(19, 10, 2024); // 这里返回的是一个固定的日期
        }
    
        // 静态方法: 判断是否是闰年
        static bool isLeapYear(int year) {
            return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
        }
    };

6.3 主函数示例

int main() {
    // 创建一个日期对象
    Date date(1, 1, 2023);
    std::cout << "日期: " << date.getDateString() << std::endl;

    // 使用静态方法获取当前日期
    Date currentDate = Date::getCurrentDate();
    std::cout << "当前日期: " << currentDate.getDateString() << std::endl;

    // 检查年份是否为闰年
    int yearToCheck = 2024;
    if (Date::isLeapYear(yearToCheck)) {
        std::cout << yearToCheck << " 是闰年。" << std::endl;
    } else {
        std::cout << yearToCheck << " 不是闰年。" << std::endl;
    }

    return 0;
}

代码解释

  1. Date 类

    • 包含三个私有成员变量 daymonth year

    • 构造函数初始化这些变量。

    • getDateString() 方法返回日期的字符串格式。

    • getCurrentDate() 静态方法返回一个固定日期的 Date 对象。

    • isLeapYear() 静态方法判断给定年份是否为闰年。

  2. main 函数

    • 创建一个 Date 对象并输出其日期。

    • 调用静态方法 getCurrentDate() 获取当前日期并输出。

    • 调用 isLeapYear() 方法判断指定年份是否为闰年。

6.4总代码与结构

#include <iostream>
#include <string>

class Date {
private:
	int day;
	int month;
	int year;

public:
	// 构造函数
	Date(int d, int m, int y) : day(d), month(m), year(y) {}

	// 获取日期字符串
	std::string getDateString() const {
		return std::to_string(day) + "/" + std::to_string(month) + "/" + std::to_string(year);
	}

	// 静态方法: 获取当前日期(假设为固定日期)
	static Date getCurrentDate() {
		return Date(19, 10, 2024); // 这里返回的是一个固定的日期
	}

	// 静态方法: 判断是否是闰年
	static bool isLeapYear(int year) {
		return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
	}
};
int main() {
	// 创建一个日期对象
	Date date(1, 1, 2023);
	std::cout << "日期: " << date.getDateString() << std::endl;

	// 使用静态方法获取当前日期
	Date currentDate = Date::getCurrentDate();
	std::cout << "当前日期: " << currentDate.getDateString() << std::endl;

	// 检查年份是否为闰年
	int yearToCheck = 2024;
	if (Date::isLeapYear(yearToCheck)) {
		std::cout << yearToCheck << " 是闰年。" << std::endl;
	}
	else {
		std::cout << yearToCheck << " 不是闰年。" << std::endl;
	}

	return 0;
}

7.总结

static 关键字在 C++ 中具有多种用法,主要用于控制变量的生命周期和作用域。通过合理使用 static,可以提高程序的效率和安全性。 


http://www.kler.cn/news/360814.html

相关文章:

  • 【Vulnhub靶场】Kioptrix Level 5
  • 【算法】深入了解 CRC 校验码的计算过程
  • 【计网笔记】应用层
  • 深度学习的高级应用
  • 1791. 找出星型图的中心节点
  • [云] Project Analysis
  • 【Vue3】将 Element Plus 引入 Vue3 项目
  • minio
  • 手机功耗技术点
  • 关于本地项目推送到Gitee时可能报的错误
  • 微软的 Drasi:一种轻量级的事件驱动编程方法
  • Go:error处理机制和函数
  • uniapp项目结构基本了解
  • 【不要离开你的舒适圈】:猛兽才希望你落单,亲人总让你回家,4个维度全面构建舒适圈矩阵
  • 肉桂酰辅酶A还原酶Cinnamoyl-CoA Reductases(CCR)表征及晶体-文献精读70
  • 三部门联合推铁路电子客票,百望云率先完成产品配置,助力财务服务数智化升级
  • 生命科学的前沿挑战与未来机遇
  • 深入了解路由
  • Spring模块详解Ⅴ(Spring ORM Spring Transaction)
  • TikTok防关联矩阵引流系统:实现tk账号自动化运营