c ++:通过指针访问主类的std :: vector的类出错了

时间:2013-04-25 13:38:13

标签: c++ pointers openframeworks

我正在使用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();
    }
}

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

this error

我看一下局部变量watch,它显示了这么大的整数值!

watch

有什么问题?

2 个答案:

答案 0 :(得分:1)

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

这意味着当您从testApp :: update()调用nrs [cnri] .branch(2,&amp; nrs)时,将修改基础数组结构。这将导致不可预测的结果,并且肯定会导致您的访问违规。

答案 1 :(得分:0)

您的问题#1是nrs[cnri].branch(2, &nrs);,在执行nrs[cnri]

时,您可能会重新分配branch()位于push_back()内的内存

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