class member是另一个类的对象

时间:2014-02-13 20:56:38

标签: c++ class opencv initializer

我是新的C ++用户......

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

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

我的班级有这个原型:

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,

2 个答案:

答案 0 :(得分:2)

您需要的是初始化列表:

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

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

答案 1 :(得分:1)

如果您希望VideoCapture成为该类的成员,您不希望在您的类定义中使用它:

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

相反,你想要这个:

VideoCapture myCapture;

然后,你的构造函数可以这样做:

myClass::myClass (string PLEASE_GIVE_ME_A_BETTER_NAME)
: myCapture(PLEASE_GIVE_ME_A_BETTER_NAME),
videoFileName(PLEASE_GIVE_ME_A_BETTER_NAME)
{
}
相关问题