更改类中的变量值并使用新值传递旧变量以供进一步使用

Change a variable value in class & pass old variable with new value for further use

本文关键字:值传 进一步 变量 新值传 变量值      更新时间:2023-10-16

当我开始使用C++时,我把所有东西都放在一个大的.cpp文件中。

我现在正试图通过为我的函数创建类来改变这一点。但我遇到了一个问题。

我有一个函数,其中有一个指数,在某些情况下应该被提高1;下次保留此值。例如,此索引用于重命名文件。像这样:

// if there's "motion" create new video file, reset index
if (numCont > 0 && contours.size() < 100) {
    index = 0;
    MotionDetector::saveFile(frame1, output_file, addFrames, video_nr);
}
// if there's a video file & no motion, raise index by 1
// if there's been no motion for x frames (that's what the index is for),
// stop recording
if (addFrames && numCont == 0) {
    index++;
    MotionDetector::saveFile(frame1, output_file, addFrames, video_nr);
    if(index == 30) addFrames = false;
}

saveFile的内部是这样的:

if (!addFrames) {
    // release old video file
    // create new file using video_nr for the naming part
}
else {
    //add frame to existing video
    video << frame;
} 

我想"全局"更改的另一个变量是布尔值。如果满足某些条件,则为true或false,并且必须保存此状态以备下次调用函数时使用。

我知道我可以返回值,然后再次从main中使用它,但我会有大约3个不同的变量(一个Mat,一个int,一个bool)要返回,我不知道如何处理。

在我把它移到自己的类之前,我仍然有两个变量来让它工作,尽管我有点认为这样做很无用。有什么简单的方法可以将函数所做的更改保存在外部类中吗?已经尝试过使用参考,但似乎也不起作用。

现在addFrames是从原始类/函数调用传递的引用参数,但它不能按预期工作。

如果您考虑将执行运动检测和维护状态的代码封装到一个类中,则不需要全局状态。你甚至可以从MotionDetector得到它,我不知道你的问题到底是什么:

class MyMotionDetector : public MotionDetector {
private:
    bool addFrames;
    int index;
    Mat mat;
public:
    MyMotionDetector () :
        MotionDetector (/* ... */), addFrames (false), index (0), mat ()
    {
        /* constructor code */
    }
    void processNewData (Contours & contours, /* whatever */) {
        /* whatever */
        if (numCont > 0 && contours.size() < 100) {
            index = 0;
            MotionDetector::saveFile(frame1, output_file, addFrames, video_nr);
        }
        /* whatever */
    }
    /* whatever methods */
    ~MyMotionDetector () :
    {
        /* destructor code */
    }
};

在考虑使用全局变量之前,请考虑这样一个问题:"为什么我不能在同一个程序中有两个全局变量,在两个不同的目录中创建文件?"。

至于从一个函数返回多个值,您要寻找的神奇短语是"多个返回值"。有几种方法可以做到这一点:

从C++函数返回多个值