简体   繁体   中英

class member is another class' object

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.

What you need is initializer list:

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

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

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)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM