你能在成员函数中创建一个静态变量吗?这个变量在该类的实例中是静态的

Can you create a static variable within a member function, that is only static within an instance of that class?

本文关键字:变量 静态 实例 函数 成员 创建 一个      更新时间:2023-10-16

我有点厌倦了总是为一个类创建一个memeber,而这个类最终只会在一个作为计数器的memeber函数中使用一次
我想知道是否有一种方法可以在类中声明一个变量,该变量仅对单个实例是静态的,下一个实例再次以0开头
因此,我基本上要寻找的是单个函数中类成员的快捷方式

我认为答案是一个非静态成员变量,但我可能误解了你的问题。

class Example
{
private:
    int mCounter;
public:
    Example() :mCounter(0)
    {
        // Empty
    }
    int increment()
    {
        mCounter++;
        return mCounter;
    }
};