c++ - 在无限循环 C++ 中定义一次变量

标签 c++ oop while-loop

我在我的项目中使用 Pylon SDK。它是 Basler 相机的 SDK。

我在 main 函数的无限 while 循环中调用 gimbalControl 函数。

gimbalControl中,我需要定义变量并初始化云台部件。之后,我在函数的其余部分使用那些初始化和定义的东西。以下是我的代码示例,用于阐明问题。

void gimbalControl(void)
{
   try
   {
        // Only executed in the first iteration
        if(!gimbalInitialized)
        {
             setupGimbal();
             configConnection(); 
             PylonInitialize();

             // Create an instant camera object with the camera device found first.
             CInstantCamera camera(CTlFactory::GetInstance().CreateFirstDevice());

             // Open the camera before accessing any parameters
             camera.Open();

             // Start the grabbing of images
             camera.StartGrabbing();

             gimbalInitialized = true;
       }
       else
       {
            // Wait for an image and then retrieve it. A timout of 5000 ms is used.
            camera.RetrieveResult(5000, ptrGrabResult, TimeoutHandling_ThrowException);  // CAUSES ERROR

            // Image not grabbed successfully?
            if (!ptrGrabResult->GrabSucceeded())
            {
                cout << "Cannot capture a frame from video stream" << endl;
            }
    }
    catch(...) // Catch all unhandled exceptions
    {
        printf("ERROR IN CAMERA CONNECTION\n");
    }
}

我试图让这个模块基于类,但我不知道如何在类中声明相机以便稍后在对象中使用。其实我不知道这种camera声明是什么!

当我编译这段代码时,我得到一个错误,提示camera was not declared in this scope问题 1:如何在此无限循环中定义一次相机而不引发此错误?

问题 2:如何将 camera 声明为类中的私有(private)变量?

最佳答案

一种方法是在 try block 之外使 camera 静态:

static CInstantCamera camera(CTlFactory::GetInstance().CreateFirstDevice());
try {
    ...
} catch (...) {
    ...
}

这确保 camera 对象只被初始化一次,并且在条件中的 else 的两侧保持可访问性。

要在您的类中声明camera,请将CTlFactory::GetInstance().CreateFirstDevice() 放入初始化列表中:

class MyClass {
private:
    CInstantCamera camera;
public:
    MyClass() : camera(CTlFactory::GetInstance().CreateFirstDevice()) {
    }
};

关于c++ - 在无限循环 C++ 中定义一次变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47928196/

相关文章:

c++ - 将 qint64 转换为 QString

c++ - ofstream 将额外的零字节写入 Unix 服务器上的文件

c# - 如何在 C# 上为包装的 C++ 方法编写签名,该方法具有指向函数及其参数的指针?

java - 为什么可以在没有实例的情况下调用方法?

C - 将字符串添加到现有数组

c++ - 如果未调用某些函数,则禁止代码编译

.net - 衡量面向对象的指标

C++ OOP 基础 - 正确返回对象引用?

loops - 如何从vimscript循环内插入文本?

c++ - 而在 C++ 中却不能正常工作