我是 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/