static member from a static member function in C++?

I wrote the following code:

class A
{
    public:
    int cnt;
    static void inc(){
        d.cnt=0;
    }
};

int main()
{
   A d;
   return 0;
}

I have seen this question:

How to call a non static member function from a static member function without passing class instance

But I don't want to use pointer. Can I do it without using pointers?

Edit:

I have seen the following question:

how to access a non static member from a static method in java?

why can't I do something like that?


No, there is no way of calling a non-static member function from a static function without having a pointer to an object instance. How else would the compiler know what object to call the function on?


Like the others have pointed out, you need access to an object in order to perform an operation on it, including access its member variables.

You could technically write code like my zeroBad() function below. However, since you need access to the object anyway, you might as well make it a member function, like zeroGood() :

class A
{
    int count;

public:
    A() : count(42) {}

    // Zero someone else
    static void zeroBad(A& other) {
        other.count = 0;
    }

    // Zero myself
    void zeroGood() {
        count = 0;
    }
};

int main()
{
    A a;

    A::zeroBad(a); // You don't really want to do this
    a.zeroGood();  // You want this
}

Update:

You can implement the Singleton pattern in C++ as well. Unless you have a very specific reason you probably don't want to do that, though. Singleton is considered an anti-pattern by many, for example because it is difficult to test. If you find yourself wanting to do this, refactoring your program or redesigning is probably the best solution.


不能使用指针,不能在静态函数中使用非静态成员变量或函数。

链接地址: http://www.djcxy.com/p/96372.html

上一篇: 没有静态成员函数的pthread

下一篇: 静态成员从C ++中的静态成员函数?