C++ Grammar Questions

Asked 2 years ago, Updated 2 years ago, 113 views

While studying openCV, I encountered the following cases.

Range r1(0, 3), r2(3, 7);
int data[] = {
    10, 11, 12, 13, 14, 15, 16,
    20, 21, 22, 23, 24, 25, 26,
    30, 31, 32, 33, 34, 35, 36,
    40, 41, 42, 43, 44, 45, 46,
};

Mat m1, m2;
m1 = Mat(4, 7, CV_32S, data);
m2 = m1(r1, r2);

The question I want to ask is the code m1(r1, r2); above.

In the form of m1(); it looks like a function. By the way, m1 is the object name.

How is this possible?

I know it's grammatically distinguishable, but I'm curious about how you can define it in that way. And I wonder what you call that definition.

At m2 = m1(r1, r2); m1 is not thought to be the overloading of the class Mat. What is that called and what grammar is that in which the instance object is a constructor?

I'd appreciate it if you could answer me.

constructor function. constructor. destructor. hmm...

c++ syntax

2022-09-22 19:05

1 Answers

Objects that can be used like functions are called functioners or function objects.

This can be used by overloading the operator().

The Mat class has Mat operator()(Range row, Range col). This operator provides more concise and intuitive access to the elements in the row.

For example, you can create a void operator()() to use the object as a function, as shown below.

#include <iostream>

struct Print {
    void operator()() {
        std::cout << "hello world" << std::endl;
    }
    void operator()(char const* str) {
        std::cout << str << std::endl;
    }
};

int main() {
    Print p;
    p();
    p("bye~");
    return 0;
}

As you can see, operator() can use several parameters, which can also be overloaded.

In addition, various operators such as operator[], operator*, operator-> can be overloaded, so please refer to the address below.

http://en.cppreference.com/w/cpp/language/operators


2022-09-22 19:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.