更新时间:2022-11-08 18:36:14
类成员函数的内存将在运行时分配,并且所有实例的类将使用相同的功能.
访问不访问成员变量的成员函数不会导致访问冲突.
因为没有与该类的实例相关的内存访问.
Memory of a class member function will be allocated at runtime, and all instance of the class will use the same function.
Accessing a member function which does not access a member variable will not cause an access violation.
Because there is no memory access related to the instance of the class.
void A::func (void)
{
cout << "hello world " <<endl;
};
将被编译为
will be compiled as
void func (A* this)
{
cout << "hello world " <<endl; // this is no where accessed here.
};
由于不能从func
访问this
in,因此调用类A的func
不会产生访问冲突.
但是,如果func
访问任何成员变量,则将创建访问冲突.原因是将发生对NULL
指针的内存访问,这将创建访问冲突.
Since this
in not accessed from func
, calling func
of class A will not create access violation.
But if func
accesses any member variable, then it will create an access violation. The reason is memory access to a NULL
pointer will happen, and it will create an access violation.
void A::func (void)
{
cout << "hello world " <<a<<endl;
};
将被编译为
will be compiled as
void func (A* this)
{
cout << "hello world " <<this->a<<endl; // Here this is used and it will create access violation.
};
要了解为什么会发生这种情况,您应该知道什么是类,什么是对象.
如果您是A类,
如果您尝试执行语句sizzeof(A),那么您将意识到这将是数据成员的大小之和
这本身意味着,仅数据成员是任何对象的一部分,而相应的功能则不是.
那么,如果函数不是对象的一部分,那么任何函数如何访问数据成员呢?
这就是著名的 this 指针出现的地方.
因此,如果有这样的代码
To understand why this happens , you should know what is a class, what is an object.
In case of your class A,
if you try to execute the statement sizzeof(A) , then you will realize it will be the sum of size of data members
This itself mean that , only data members are part of any object and the corresponding functions are not.
Then how does any function accesses the data members if it is not a part of object ?
This is where famous this pointer comes into picture.
Hence if there is a code like
A *ptr = new A();
ptr->func();
此代码将由编译器转换为
This code will be converted by compiler to
A *ptr = new A();
func(ptr); //Here ptr points to the object.
因此,您的func函数将使用传递的ptr(即 this 指针)访问数据成员.
Hence your func function will access data members using the passed ptr (i.e. this pointer )
void func( A* this )
{
printf("Some text");
}
如果我们选择将ptr的初始化替换为 NULL ,那么我们将向函数传递 NULL 指针.
if we chose to replace initialization of the ptr to NULL then we will be passing a NULL pointer to function.
A *ptr = NULL;
ptr->func();
编译器会将这段代码转换为
Compiler will convert this code to
A *ptr = NULL;
func(ptr);
在func中,如果您尝试访问任何数据成员
In func, if you try to access any data member
A::func()
{
printf( "a = %d", a);
}
编译器会将这段代码转换为
compiler will convert this code to
func( A* this )
{
printf("a = %d", this->a);
}
现在您可以观察到,因为我们正在向函数发送NULL指针.它必须崩溃:)
Now you can observe that , as we are sending NULL pointer to the function. It has to crash :)
阅读此 link [ ^ ]在堆栈溢出中,这将清除很多问题,并在您的脑海中引发很多问题:)
read this link[^] in stack overflow it will clear up lots of issue and also raise lots of question in your mind too :)