简体   繁体   中英

How to access a non-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.

如果不使用指针,则不能在静态函数内使用非静态成员变量或函数。

You don't need a pointer per se, but you do need access to the object through which you are accessing the non-static variable. In your example, the object d is not visible to A::inc(). If d were a global variable rather than a local variable of main, your example would work.

That said, it's curious why you'd want to go to any great effort to avoid using pointers in C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM