c++ - 类成员是另一个类的对象

标签 c++ class opencv initializer

我是 C++ 新用户...

我有一个关于如何声明类“classA”的成员的问题,该成员是另一个类“classB”的对象,知道“classB”有一个采用字符串参数的构造函数(除了默认构造函数).我在网上做了一些关于这个问题的研究,但是它并没有帮助我解决我正在处理的问题。

更具体地说,我想创建一个具有 VideoCapture 对象作为成员的类(VideoCapture 是一个提供视频流的 openCV 类)。

我的类(class)有这个原型(prototype):

class  myClass {
private:

string videoFileName ;

public:

myClass() ;

~myClass() ;

myClass (string videoFileName) ;
// this constructor will be used to initialize myCapture and does other
// things

VideoCapture myCapture (string videoFileName /* :  I am not sur what to put here */ )  ;

};

构造函数是:

myClass::myClass (string videoFileName){

VideoCapture myCapture(videoFileName) ;
// here I am trying to initialize myClass' member myCapture BUT
// the combination of this line and the line that declares this
// member in the class' prototype is redundant and causes errors...

// the constructor does other things here... that are ok...

}

我已尽力以最简单的方式揭露我的问题,但我不确定我是否成功...

感谢您的帮助和解答。

L.

最佳答案

你需要的是初始化列表:

myClass::myClass (string videoFileName) : myCapture(videoFileName) {
}

这将使用其带有 string 参数的构造函数构造 myCapture

关于c++ - 类成员是另一个类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21765324/

相关文章:

c++ - cvCreateMat 内存泄漏(OpenCV)

c++ - 基类 'Interpreter' 没有非析构函数虚函数

c++ - 警告 C4407 会导致什么问题?

C++虚拟继承内存布局

c++ - OpenCV 透视图

c++ - OpenCV (C++) - 从已知的 3D 对象和相机位置计算图像的 2D 坐标

c++ - open-std.org 是 C++11 标准文档的官方网站吗?

php spl_autoload_register() 不加载类

vb.net - 在另一个类中声明一个类的目的是什么?

python - Python 中的私有(private)类变量?