Questions about C + + static member functions accessing Non-static member variables _c language

Source: Internet
Author: User

Copy Code code as follows:

Class A
{
Public
Static Functiona ()
{
Menber = 1;
}

Private
int menber;
}


There was an error compiling the above code. The reason is simple, as you all know, static member functions cannot access non-static members because static functions belong to the class and not to the entire object, and members in static functions may not have memory allocated. A static member function has no implied this argument. As a result, it cannot access non-static members of its own class.

What do you do if you want to visit? Earth people know that as long as they will:

Copy Code code as follows:

int menber;
Change the line above to:
static int menber;

But this approach allows us to make the member variables used in the static function static, and the static members have to be explicitly initialized, is there a better way? The answer is yes. Code to speak:
Copy Code code as follows:

Class A
{
Public
Static Functiona (A * _a)
{
_a-> menber = 1;
Cout<<_a-> menber<<endl;
_a->f ();
}
void F ()
{
cout<< "F was called" <<endl;
}
Private
int menber;
};

The premise is that this class has to allocate memory space. What I'm actually doing here is to use an object pointer as the "This" pointer to a static member function, which is intended to mimic passing the this variable in a Non-static member function (which in a Non-static member function appears to be in ecx).

The idea was created when I had to createthread in a class, because the thread funtion was all about static. I don't know why I wrote the Code,thread is static. Forgot where to see the request. Have time to find out why).

Visible C + + is very flexible.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.