Please could someone explain to me what this operator does in C++ at a function?

class simplecanny
{
    ros::NodeHandle nh_;
    ros::NodeHandle n;
    ros::Publisher pub ;
    image_transport::ImageTransport it_;    
    image_transport::Subscriber image_sub_; //image subscriber 
    image_transport::Publisher image_pub_; //image publisher(we subscribe to ardrone image_raw)
    std_msgs::String msg;
    public:
    *** simplecanny()
        : it_(nh_) ***
    {
        image_sub_ = it_.subscribe("/ardrone/image_raw", 1, &simplecanny::imageCb, this);
        image_pub_= it_.advertise("/arcv/Image",1); 
    }

    ~simplecanny()
    {
        cv::destroyWindow(WINDOW);
    }

    ...

At the simplecanny() : it_(nh_) constructor, Im not familiar with the : it_(nh_) part. What does it do? Is that a case of operator overloading?

Thanks in advance!

有帮助吗?

解决方案

This is called the constructor initializer list. It gives the parameters to be passed to the constructors of the base classes and members of the class.

In your example, it is passing nh_ to the constructor of it_.

Any base class or member that does not appear in this list is constructed using their respective default constructors.

其他提示

Call the superclass constructor in the subclass' initialization list.

The single colon (:) is no operator but a part of the language, indication the start of an initialization list. The initialization list can be used only in constructors and is used to initialize the object's member variables and superclass subobjects. In your case, the member variable it_ is initialized with nh_. You might want to look up initialization lists and constructors in the texbook of your choice.

It is the member-initialization-list. It permits to pass the correct parameters and chose the good constructor for the members of the class and the constructor of the base classes.

The standard says:

12.6.2 Initializing bases and members [class.base.init]

In the definition of a constructor for a class, initializers for direct and virtual base subobjects and non-static data members can be specified by a ctor-initializer, which has the form

ctor-initializer:
   : mem-initializer-list

Any members or base class not specified in the member-initialization-list will use its default constructor.

In you case, you are passing nh_ to the constructor of image_transport::ImageTransport to initialize it_.

The column represents a start of an initialization list. It is used for setting up the variables of objects. Its another important and useful feature is invocation of desired constructor of based class which this class derives. The detailed answer and reason why it is introduced to C++ can be found at Constructor initialization lists and invocation of desired constructor of based class

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top