简体   繁体   English

通过引用将向量传递给类

[英]Passing a vector to a class by reference

I have a vector of ofTextures called images. 我有一个称为图像的ofoftextures向量。 I want to pass this to a class called Section by reference so it is not copied. 我想将此传递给按引用命名的类,这样就不会被复制。

images is created in the header file. 在头文件中创建图像。 images has textures created inside of it, in the draw method with: 在draw方法中,图像具有在其中创建的纹理:

void ofApp::draw(){
if (video0.isFrameNew()){
    ofPixels pixels = video0.getPixels();
    images.emplace_back();
    images.back().allocate(pixels);
    }
}

I have a getTextures() function to return my images by reference I think the vector should still exist as I have initialised it before using it in this function. 我有一个getTextures()函数通过引用返回我的图像,我认为该矢量应该仍然存在,因为在此函数中使用它之前,我已经对其进行了初始化。

vector<ofTexture> &ofApp::getTextures(){
    return  images;
}

I use this in the call to my constructor which is in a for loop in void ofApp::setup() 我在对构造函数的调用中使用了此函数,该构造函数在for循环中无效ofApp::setup()

imSec.push_back(Section(getTextures());

I use getTextures() to pass the vector into my call to my constructor; 我使用getTextures()将向量传递到对构造函数的调用中; however, when I run my program I don't seem to be able to draw the contents of the vector as I don't think my reference to the vector is working. 但是,当我运行程序时,我似乎无法绘制矢量的内容,因为我认为对矢量的引用不起作用。

Any help on the correct way to pass by reference would be great. 关于通过引用的正确方法的任何帮助都将非常有用。

The function getTexture() must return a reference to a vector that exists after the function returns. 函数getTexture()必须返回对该函数返回后存在的向量的引用。 If you declare a vector inside that function and return a reference to it, it will not work, since the vector's memory in invalidated after the function returns. 如果在该函数内声明一个向量并返回对其的引用,则它将不起作用,因为在函数返回后向量的内存将失效。

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

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