A static member function in C++ accesses an instance of a non static member
- 2020-05-26 09:47:03
- OfStack
Static member functions in C++ access instances of non-static members
Implementation code:
#include <iostream>
/*
Static member functions can only access functions and data other than static data members, static member functions, and classes. They cannot access non-static data members, but static member functions or static data members can be accessed by any function with permission. The reason is: the address of the current object ( this ) is implicitly passed to the function being called. but 1 None of the static member functions this Pointer, so it cannot access non-static member functions.
*/
class a
{
public:
static void FunctionA()// Static member functions are not implicit this The independent variables
{
//menber = 1;//error C2597: For non-static members "a::member" Illegal citation
//printValue();//error C2352: " a::printValue " : An illegal call to a non-static member function
}
void printValue()
{
printf("menber=%d\n",menber);
}
private:
int menber;
};
/* How do I access non-static members?
1. Changes a non-static member to a static member. Such as :static int member;// It's not going to go wrong, but it's going to go wrong
2. Take an object as a parameter and access the non-static members of the object by its name
*/
class A
{
public:
A():menber(10){}
static void FunA(A& _A)
{
_A.menber = 123;
_A.printValue();
}
static void FunB(A* _A)
{
_A->menber = 888;
_A->printValue();
}
void printValue()
{
printf("menber=%d\n",menber);
}
private:
int menber;
};
int _tmain(int argc, _TCHAR* argv[])
{
A* m=new A();
m->FunB(m);
A::FunB(m);
A::FunA(*m);
A b;
b.FunA(b);
A::FunB(&b);
b.FunB(&b);
m->FunB(&b);
return 0;
}
Thank you for reading, I hope to help you, thank you for your support of this site!