c++ - 其他类的二传手

标签 c++

我有一个名为“StatusInformation”的类,我想在其中将变量 _status 设置为 true/false,但我只得到“segmentation fault”。我认为 _status 不存在,因为我从另一个类(class)调用它。有人知道如何防止这个错误吗?

状态信息.cpp

void StatusInformation::SetClientConnectStatus(bool status)
{
    _status = status;
}

状态信息.h

class StatusInformation
{
private:

    bool _status = false;

public:

    void SetClientConnectStatus(bool status);
};

来电类.cpp

_statusInformation = new StatusInformation();

_statusInformation->SetClientConnectStatus(true);

调用类.h

StatusInformation *_statusInformation;

最佳答案

编辑:指向您的代码的链接只是给我缺少 ArduinoProtocol 的代码。

对我来说,它编译时带有 2 个关于非静态数据成员初始值设定项的警告,然后运行正常。我真的不相信段错误会来自这段代码。唯一可能导致的是如果

_statusInformation = new StatusInformation();

失败并返回 0,使您的指针成为 NULL 指针。导致:

_statusInformation->SetClientConnectStatus(true);

相当于:

NULL->SetClientConnectStatus(true);

但这只有在您选择使用 no-throw new 时才会发生。你详细说明了哪一个。所以实际上,该代码中唯一可能导致段错误的事情不可能发生。最坏的情况将抛出 std::bad_alloc。

关于c++ - 其他类的二传手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29979800/

相关文章:

可变参数包之前的 C++11 默认模板参数

c++ - 在不释放所有动态分配的资源的情况下结束程序是否有风险?

c++ - glPolygonMode(GL_FRONT_AND_BACK, GL_LINES) 不工作

c++ - 如何在 C++ 中显示变量

c++ - 如何在 C++ 正则表达式中第一次匹配时停止?

c++ - 类方法作为函数参数

c++ - 多个函数定义错误

c++ - 了解内存分配的工作原理 (LLVM)

c++ - 声明语法错误

c++ - 覆盖基类返回类型