gpt4 book ai didi

c++ - 一个函数可访问的类变量或成员函数中仍然是对象感知的静态变量

转载 作者:太空狗 更新时间:2023-10-29 19:51:59 25 4
gpt4 key购买 nike

成员函数中的静态变量是类级变量,这意味着所有类实例都访问同一个变量。

class foo{
int doingSomething(){
static int count =0;
static int someValue=0
count++;
if(count%10 == 0){
someValue *= counter;
}
someValue += counter;
return someValue * 2;
}
}

我想要一种方法来计算在每个 foo 实例中分别调用 count() 的次数,我可以这样做:

class foo{
int count;
int someValue;
int doingSomething(){
count++;
if(count%10 == 0){
someValue *= counter;
}
someValue += counter;
return someValue * 2;
}

但我对这种方法的问题是 countsomevalue 仅在 foo 中由 doingSomething() 使用和访问,所以有没有理由让它成为成员变量,因为它打开了它被其他类成员函数修改和使用的大门,我想防止这种情况发生。有没有我缺少的解决方案?


编辑 1:这个想法是计算 doingSomething()Foo 的每个实例中被调用的次数,这个值将仅由“doingSomething()”用于计算其他值,每个实例都不同。

为什么?doingSomething() 计算一个 int someVariable 第一次被调用,然后存储它以备后用,这个存储的值被 doingSomthing() 使用每次调用 10 次,每一次 11 调用 int someVariable 都会重新计算并使用这个新值...过程无限重复。

最佳答案

你可以在基类中隐藏你的计数器

class base_foo
{
public:
void doSomething()
{
counter++;
//other fun stuff
}

private:
int counter;
};

class foo : base_foo
{
public:
foo()
{
doSomething();
}
// your other code
};

关于c++ - 一个函数可访问的类变量或成员函数中仍然是对象感知的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33000459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com