Static member functions in C ++ access non-static member variables

Source: Internet
Author: User

 

In C ++, when a static member function accesses a non-static member variable, first look at a classclass
{
Public:
Static functiona ()
{
Menber = 1;
}

PRIVATE:
Int menber;
}

An error occurred while compiling the above Code. The reason is simple. As we all know, static member functions cannot access non-static members. This is because static functions belong to Classes rather than the entire object, and member in static functions may not be allocated memory. The static member function does not have an implicit this independent variable. Therefore, it cannot access non-static members of its own class. (I have read a good article "This pointer in C ++" to introduce the details of this aspect)

What should I do if I want to access it? Everyone on Earth knows that as long:

Int menber;
// Change the line above:
Static int menber;

However, this method forces us to convert all the member variables used in the static function into static ones, and the static members must be explicitly initialized. Is there a better way? The answer is yes. Code statement:

Class
{
Public:
Static functiona (A * _)
{
_ A-> menber = 1;
Cout <_ A-> menber <Endl;
_ A-> F ();
}
Void F ()
{
Cout <"f called" <Endl;
}
PRIVATE:
Int menber;
};

The premise is that the class has to allocate memory space. In fact, what I do here is to use an object pointer as the "This" pointer of a static member function, it is intended to simulate the transfer of this variable in non-static member functions (this pointer exists in non-static member functions (push seems to be in ECx ))

This idea is generated when createthread is required in a class, because the thread funtion requires static (yes? I don't know why the code I wrote is static. I forgot where I saw this requirement. Find the reason ).

It can be seen that 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.