类访问冲突 C++
class Register
{
private:
DWORD ax,dx,cx,bx; // POH
DWORD bp,sp;
DWORD flag, ip;
public:
//====================================================
Register()
{
ax = 0x0;
dx = 0x0;
cx = 0x0;
bx = 0x0;
bp = 0x0;
//memset(&this->sp,0,sizeof(sp));
sp = 0x0;
flag = 0x0;
ip = 0x0;
}
//====================================================
~Register()
{
}
//====================================================
void setAx(DWORD d)
{
ax=d;
}
//====================================================
DWORD getSp()
{
return sp;
}
}*PReg;
为什么函数 getSp();
会给出访问冲突错误?
class Register
{
private:
DWORD ax,dx,cx,bx; // POH
DWORD bp,sp;
DWORD flag, ip;
public:
//====================================================
Register()
{
ax = 0x0;
dx = 0x0;
cx = 0x0;
bx = 0x0;
bp = 0x0;
//memset(&this->sp,0,sizeof(sp));
sp = 0x0;
flag = 0x0;
ip = 0x0;
}
//====================================================
~Register()
{
}
//====================================================
void setAx(DWORD d)
{
ax=d;
}
//====================================================
DWORD getSp()
{
return sp;
}
}*PReg;
Why does function getSp();
gives an Access Violation error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您忘记实例化您的类。您已经创建了一个指向 Register 类的指针的变量,但尚未实例化它。
您得到的是一个指针,该指针要么为空,要么指向某个随机内存位置,并且您假设它指向该类的实例。因此,当您尝试访问任何成员变量时,您实际上正在访问您无权访问的内存位置。
您需要做的是创建该类的一个新实例:
我可以同时建议您将变量声明从类原型中移开(我假设它位于您的头文件中)。
You have forgotten to instantiate your class. You have made a variable that is a pointer to the class Register, but you have not instantiated it.
What you get is a pointer that is either null or pointing to some random memory location, and you are assuming that it is pointing to your instance of the class. So when you try to access any of the member variables your are actually accessing memory locations you do not have access to.
What you need to do is create a new instance of the class:
May I at the same time suggest that you move the variable declaration away from the class prototype (which I assume resides in your header file).