当我开始使用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,并且必须保存此状态,以便下次调用该函数。
我知道我可以返回值,然后再次从我的主要使用它然后我有〜3个不同的变量(一个Mat,一个int,一个bool)返回,我不知道如何处理
在我把它移到自己的课程之前,我仍然有2个变量使它工作,尽管我有点认为这样做是没用的。有没有简单的方法来保持外部类中的函数所做的更改?已经尝试使用引用,但它似乎也没有用。
现在addFrames是从原始类/函数调用传递的引用参数,但它不能按预期工作。
答案 0 :(得分:1)
如果您认为代码正在执行运动检测并将状态保存到类中,则不应该需要全局状态。您甚至可以从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 */
}
};
在考虑使用全局变量之前,请考虑像这样的问题,为什么我可能在同一个程序中没有两个,在两个不同的目录中创建文件?“正确设计对象可能意味着像计数器和状态布尔值这样的东西与需要管理它的代码保持一致。并且您可以更灵活地实例化多个。
对于从函数返回多个值,您正在寻找的神奇短语将是“多个返回值”。有几种方法可以做到: