0
class Foo
{
public:
    void bar();
};

void Foo::bar()
{
    static int n = 0;

    printf("%d\n", n++);
}

int main(int argc, char **argv)
{
    Foo *f = new Foo();
    f->bar();
    delete f;
    f = new Foo();
    f->bar();
    delete f;

    return 0;
}

Does n reset to 0 after delete'ing and new'ing the class over again? Or is n effectively a static class member (same reference in all instances)?

In other words, should I get

0
0

or

0
1

?

4

3 回答 3

4

As the variable is static in the function, it will be 0, 1 as the memory is not delete as it is static, even if the variable is part of a function and not part of the class.

Even when you delete an instance of a class, the functions still remain in memory for the class as they can be used by other instances of the class.

于 2009-08-29T02:55:15.773 回答
0

0 1

'n' is effectively a static class member with a different scope. Its essentially the same as a static variable in a function of any other context (member function, global, etc)

于 2009-08-29T02:57:02.680 回答
0

'n' is a static variable in the function Foo::bar. There is only ever one copy of that function, regardless of how many Foo instances you might create or destroy.

于 2009-08-29T02:57:39.577 回答