【问题标题】:c++: a class accessing an std::vector of main class by pointers goes wrongc ++:通过指针访问主类的std :: vector的类出错
【发布时间】:2013-04-25 21:46:02
【问题描述】:

我正在使用 VS2012 Express、Platform Toolset v100 和 openFrameworks 0.7.4 构建我的 C++ 项目。

我有一个名为NameRect 的类,这是.h 文件的一部分:

void config(int cx, int cy, int cw, int ch, std::string cname) {
    x = cx;
    y = cy;
    w = cw;
    h = ch;
    name = cname;

    dead = false;
}

void branch(int iterants, std::vector<NameRect> *nrs) {
    for (int i = 0; i < iterants; i++) {
        NameRect nnr;
        nnr.config(x + w, y - iterants * h / 2 + i * h, w, h, "cb");

        children.push_back(nnr);
        nrs->push_back(nnr);
    }
}

void render() {
    if (!dead) {
        ofSetColor(ofRandom(0, 255), ofRandom(0, 255), ofRandom(0, 255), 0);
        ofRect(x, y, w, h);
    }
}

我的testApp.cpp中有代码:

//--------------------------------------------------------------
void testApp::setup(){
    ofSetWindowShape(800, 600);

    nr.config(0, 300, 50, 10, "cb");
    nrs.push_back(nr);
}

//--------------------------------------------------------------
void testApp::update(){
    if (ofRandom(0, 50) <= 1 && nrs.size() < 100) {
        for (int cnri = 0; cnri < nrs.size(); cnri++) {
            if (ofRandom(0, nrs.size() - cnri) <= 1) {
                nrs[cnri].branch(2, &nrs);
            }
        }
    }
}

//--------------------------------------------------------------
void testApp::draw(){
    for (int di = 0; di < nrs.size(); di++) {
        nrs[di].render();
    }
}

当我实际构建(成功)这个项目并运行它时,它给了我这样一个错误:

我看看局部变量手表,它显示了如此大的整数值!

有什么问题?

【问题讨论】:

  • 它表示您的程序正在写入0x00000008,这几乎可以肯定意味着您正在访问NULL 指针。你确定一切都已经初始化了吗?
  • 哪里出现错误(哪一行代码)?上下文是什么?
  • 初始化是指std::vector?

标签: c++ pointers openframeworks


【解决方案1】:

branch() 正在修改作为第二个参数传入的向量数组。

这意味着当您从 testApp::update() 调用 nrs[cnri].branch(2, &nrs) 时,底层数组结构会被修改。这将导致不可预知的结果,并且肯定会导致您的访问冲突。

【讨论】:

    【解决方案2】:

    您的问题 #1 是 nrs[cnri].branch(2, &amp;nrs);,您可能会在执行 push_back() 时从 branch() 内部重新分配 nrs[cnri] 所在的内存

    您的问题 #2 是您定义函数的方式,一旦您开始将标头包含到多个 cpp 文件中,您将面临该问题。如果您在标题中定义它们,请放入“内联”,否则您将在多个位置定义相同的函数。

    【讨论】:

    • 好的。我想我明白了。那我如何才能从NameRect.h 访问nrs
    猜你喜欢
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多