类访问冲突 C++

发布于 2024-12-11 14:47:34 字数 886 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人生百味 2024-12-18 14:47:34

您忘记实例化您的类。您已经创建了一个指向 Register 类的指针的变量,但尚未实例化它。

您得到的是一个指针,该指针要么为空,要么指向某个随机内存位置,并且您假设它指向该类的实例。因此,当您尝试访问任何成员变量时,您实际上正在访问您无权访问的内存位置。

您需要做的是创建该类的一个新实例:

PReg = new 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:

PReg = new Register();

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文