更改类中的变量值并使用新值传递旧变量以供进一步使用
Change a variable value in class & pass old variable with new value for further use
当我开始使用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++函数返回多个值
相关文章:
- 为什么可以将左值传递给"std::async",即使它引用了右值
- 当值传递给C++中的运算符重载函数时会发生什么
- 如何将非可变参数值传递给 fmt::format?
- 将 qml 项目值传递给 cpp 后如何与它们进行交互?
- NDK:将文本字段值传递给 c++ 字符串
- 如何将值传递给 lambda 函数
- 如何在C++中将std::string值传递给RegSetValueEx()
- 如何将 c ++ 变量的值传递给 hadoop HDFS 的 bash 系统命令?
- C++ 通过参数将值传递给 char 数组
- 如何将值传递给MFC消息映射函数on_command
- 使用JNI将长值传递给Java
- 如何在不使用 Argv 和 Argc 的情况下将 Sum 值传递给 C++ 程序
- C++ 将值传递给 fStream
- 如何将函数中的多个值传递给C++中的不同函数
- 将多个解析值传递给 addPositionalArgument 函数
- C++为什么将左值传递给move构造函数对模板有效
- 一种自动检测对象的方法,该方法通过值传递给c++中的函数
- 将值传递给main(int,char**)
- 将大于long类型的最大值的值传递给C中的fseek
- 将值传递给atexit