C++ "Getter"方法在尝试返回同一类中的私有(private)变量时抛出访问冲突

标签 c++ get private access-violation

我遇到的问题是,每当我的代码中的“getter”方法试图返回它为其设计的变量时,它就会抛出访问冲突异常。我在下面包含了构造函数,因为最后一行(cout)不会导致访问冲突。 LinkedNode 是一个头文件。

#ifndef _LinkedNodeClass_
#define _LinkedNodeClass_

#include <iostream>
#include <string>
using namespace std;

class LinkedNode {
public:

LinkedNode(string first, string last, int ID, LinkedNode* rightNode, LinkedNode* leftNode)
{
    Fname = first;
    Lname = last;
    EID = ID;
    right = rightNode;
    left = leftNode;

    cout<<"LNODE EID: "<<EID<<endl;  //Does not cause access violation
}

int getEID()
{
    return EID;  //Does cause access violation
}

private:

string Fname;
string Lname;
int EID;
LinkedNode *right;
LinkedNode *left;

};

#endif

LinkedNode 对象由一个名为 head 的 LinkedNode 指针指向。这是使用 LinkedNode 的类中的代码:

#include <iostream>
#include <fstream>
#include <string>
#include "LinkedNode.h"

using namespace std;

class MJCTree
{
private:
LinkedNode* head;
int size;

public:
MJCTree()
{
            head = 0;  //not sure how to null.
    size = 0;
}

void insert(string first, string last, int bEID)
{
    if(size == 0)
    {
        head = new LinkedNode(first, last, bEID, 0, 0);
        ++size;
    }
}

int getFirst() //This method leads to the Access Violation
{
    return head->getEID();
}
};

和异常:

First-chance exception at 0x013821f6 in Project 3.exe: 0xC0000005: Access violation reading location 0xcccccd0c.
Unhandled exception at 0x013821f6 in Project 3.exe: 0xC0000005: Access violation reading location 0xcccccd0c.

最佳答案

您的 LinkedNode 类看起来不错,但您的 MJCT 类很危险。 getFirst 方法使用 head,但不能保证 head 已经被 初始化。 MJCTree 构造函数不会初始化它,如果您还没有 尚未调用插入,您可能会遇到访问冲突。

类构造函数应该初始化一个对象并使其处于可以安全使用的状态。您的 MJCTree 构造函数不会这样做,因为对 getFirst 函数的调用将使用空(或以前未初始化的)指针。您可以修改构造函数,以便它分配一个 head 节点供 getFirst 使用。或者您可以修改 getFirst,以便通过添加对 size>0head!=0 的检查,即使 head 为 null 也可以安全调用。如果该检查失败,则不能使用 head 并且需要返回错误或抛出异常。

我们需要查看创建 MJCTree 实例并调用 getFirst 的代码,以便准确判断出了什么问题,但设计一个可以安全/正确使用的类更为重要。

关于C++ "Getter"方法在尝试返回同一类中的私有(private)变量时抛出访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22522615/

相关文章:

c++ - Opengl 3D 立方体无法在 Windows 上正确呈现

java - 如何从ArrayList中获取特定对象

node.js - 如何在node js中使用express重定向后app.get

c# - 如何从具有多对多关系的 C# Web API Visual Studio 2017 RTM 服务(GET)复杂(嵌套)JSON?

php - PHP中可以使用私有(private)常量吗?

c++ - libgit : Fastest way of fetching files in a commit

c++ - 逐字符读取文本文件

ios - 当 iOS 中的简单实例变量完成相同的工作时,为什么我们在 .m 文件中创建私有(private)属性?

c++ - 在 C++ 中,为什么分组没有被语言强制应用于类/结构的公共(public)、私有(private)和 protected 成员?

模板构造函数中的 C++ 链接器错误 : "unresolved external symbol"