class member is another class' object

做~自己de王妃 提交于 2019-12-04 06:28:14

问题


I am a new C++ user...

I have a question regarding how to declare a member of a class "classA" that is an object of another class "classB", knowing that "classB" has a constructor that takes a string parameter (in addition to the default contructor). I did some research online about this issue however it did not help much to help me fix the issue I'm dealing with.

To be more specific, I want to create a class that has as member a VideoCapture object (VideoCapture is an openCV class that provide a video stream).

My class has this 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 */ )  ;

};

the constructor is :

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...

}

I did my best to expose my issue in the simplest way, but I'm not sure I managed to...

Thank you for your help and answers.

L.


回答1:


What you need is initializer list:

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

This will construct myCapture using its constructor that takes a string argument.




回答2:


If you want a VideoCapture to be a member of the class, you don't want this in your class definition:

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

Instead you want this:

VideoCapture myCapture;

Then, your constructor can do this:

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


来源:https://stackoverflow.com/questions/21765324/class-member-is-another-class-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!