问题描述
这是我的导师提供的一段代码,用于分析和说明其行为的原因.作为一个初学者,我对代码的运行情况感到有些惊讶,因为指向类对象的指针已设置为NULL.
我很少用代码玩,在网上搜索后得出结论,对该函数的调用被隐式地实现为void funct(A * this),这就是为什么它可以正常工作的原因.
This is piece of code given by my mentor to analyse and state the reason behind its behaviour.
Being a beginner, I was a little surprised to see this code running fine, as pointer to the object of class has been set NULL.
I played with the code little, searched the web and came to a conclusion that the call to the function is being implicitly implemented as void funct(A* this) that is why it is working fine.
#include<iostream>
using namespace std;
class A
{
public:
int a;
void func (void)
{
cout << "hello world " <<endl;
};
};
int main()
{
A* ptr = NULL;
ptr->func();
return 0;
}
但是我的导师告诉我,这不是这段代码可以正常工作的原因,如果这是导致代码崩溃的原因,请补充.并添加了
上面代码中的cout语句为"a".
But my mentor told me that this is not the reason for this piece of code working fine and added if this is the reason then why does this code crashes. And added
"a" to the cout statement in the above code.
void func (void)
{
cout << "hello world " << a <<endl;
};
现在我有些困惑,无法以其他任何方式看到它.
任何人都可以提供我可以解决的任何方向或暗示.
Now I am a little puzzled and not able to see it in any other way.
Can anyone provide any direction or any hint taking which I can work forward to solve it.
推荐答案
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 *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(即指针)访问数据成员.
Hence your func function will access data members using the passed ptr (i.e. pointer )
void func( A* this )
{
printf("Some text");
}
如果我们选择将ptr的初始化替换为,那么我们将向函数传递指针.
if we chose to replace initialization of the ptr tothen we will be passing a 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 :)
这篇关于C ++输出问题.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!