繁体   English   中英

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

[英]c++: a class accessing an std::vector of main class by pointers goes wrong

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

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

这个错误

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

看

问题是什么?

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

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

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

问题2(开始包含多个cpp文件的标头后将面临)是定义函数的方式。 如果您在标头中定义它们,请在行中放入“ inline”,否则将在多个位置定义相同的函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM