C++ 中 static 关键字

修饰普通变量,修改变量的存储区域和生命周期,使变量存储在静态区,在 main 函数运行前就分配了空间,如果有初始值就用初始值初始化它,如果没有初始值系统用默认值初始化它。
修饰普通函数,表明函数的作用范围,仅在定义该函数的文件内才能使用。在多人开发项目时,为了防止与他人命名空间里的函数重名,可以将函数定位为 static。
修饰成员变量,修饰成员变量使所有的对象只保存一个该变量,而且不需要生成对象就可以访问该成员。
修饰成员函数,修饰成员函数使得不需要生成对象就可以访问该函数,但是在 static 函数内不能访问非静态成员。

以下是对上述关于 static 修饰不同内容的详细解释及示例:

一、修饰普通变量

static 修饰普通变量时,这个变量被存储在静态存储区。它在程序开始运行前就分配空间,并且在整个程序的生命周期内都存在。如果有初始值,就用初始值初始化;如果没有初始值,系统会用默认值初始化。

例如:

#include <iostream>

void testFunction() {
    static int staticVariable = 0;
    std::cout << "Static variable: " << staticVariable << std::endl;
    staticVariable++;
}

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

在这个例子中,函数 testFunction 中的静态变量 staticVariable 只在第一次调用函数时初始化一次,后续调用不会再次初始化,而是保留上次调用后的值。每次调用函数时,staticVariable 的值会递增。

二、修饰普通函数

static 修饰普通函数可以限制函数的作用范围,使其仅在定义该函数的文件内可见。在多人开发项目时,这有助于避免函数名冲突。

例如:

// file1.cpp
static void file1Function() {
    std::cout << "This is a function in file1." << std::endl;
}

// file2.cpp
static void file2Function() {
    std::cout << "This is a function in file2." << std::endl;
}

在这个例子中,file1Functionfile2Function 分别在不同的文件中定义为 static,它们只能在各自的文件内被调用,其他文件无法访问这些函数。

三、修饰成员变量

static 修饰成员变量时,所有的对象共享同一个变量。它不属于任何一个特定的对象,而是属于整个类。不需要生成对象就可以通过类名直接访问该成员变量。

例如:

#include <iostream>

class MyClass {
public:
    MyClass() {
        count++;
    }
    static int getCount() {
        return count;
    }
private:
    static int count;
};

int MyClass::count = 0;

int main() {
    MyClass obj1;
    MyClass obj2;
    MyClass obj3;

    std::cout << "Number of objects created: " << MyClass::getCount() << std::endl;
    return 0;
}

在这个例子中,count 是静态成员变量,用于记录创建的对象数量。每个对象的构造函数都会增加 count 的值。可以通过静态成员函数 getCount 来访问静态成员变量 count,而不需要创建对象。

四、修饰成员函数

static 修饰成员函数使得不需要生成对象就可以访问该函数。但是,在静态成员函数内不能访问非静态成员,因为静态成员函数不依赖于特定的对象,而非静态成员属于特定的对象。

例如:

#include <iostream>

class MyClass {
public:
    static void staticFunction() {
        // 不能访问非静态成员变量和成员函数
        // std::cout << nonStaticVariable << std::endl;
        // nonStaticFunction();
        std::cout << "This is a static function." << std::endl;
    }
    void nonStaticFunction() {
        std::cout << "This is a non-static function." << std::endl;
    }
private:
    int nonStaticVariable = 10;
};

int main() {
    MyClass::staticFunction();
    return 0;
}

在这个例子中,静态成员函数 staticFunction 不能访问非静态成员变量 nonStaticVariable 和非静态成员函数 nonStaticFunction

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值