Function overloading

cv::Mat是opencv中最基础的数据类型,表示一个矩阵

  1. Mat add(Mat& A, Mat& B);
  2. Mat add(Mat& A, float b);
  3. Mat add(float a, Mat& B);
  4. Mat mul(Mat& A, Mat& B);
  5. Mat mul(Mat& A, float b);
  6. Mat mul(float a, Mat& B);
  7. ...

一系列函数有相同的函数名,但是函数列表不同,就叫做函数的重载。
More convenient to code as follows

  1. Mat A, B;
  2. float a, b;
  3. //…
  4. Mat C = A + B;
  5. Mat D = A * B;
  6. Mat E = a * A;
  1. #include <iostream>
  2. #include <opencv2/opencv.hpp>
  3. using namespace std;
  4. int main()
  5. {
  6. float a[6]={1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f};
  7. float b[6]={1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f};
  8. cv::Mat A(2, 3, CV_32FC1, a);
  9. cv::Mat B(3, 2, CV_32FC1, b);
  10. cv::Mat C = A * B;
  11. cout << "Matrix C = " << endl
  12. << C << endl;
  13. return 0;
  14. }

image.png

Operator overloading 运算符重载

  • Customizes the C++ operators for operands of user-defined types.
  • Overloaded operators are functions with special function names:

    std::string s("Hello ");
    s += "C";
    s.operator+=(" and CPP!");
    

    image.png
    Implementation of operator+() and operator+=() ```cpp class MyTime { int hours; int minutes; public: MyTime(): hours(0), minutes(0){} MyTime(int h, int m): hours(h), minutes(m){}

    MyTime operator+(const MyTime & t) const {

      MyTime sum;
      sum.minutes = this->minutes + t.minutes;
      sum.hours = this->hours + t.hours;
      sum.hours += sum.minutes / 60;
      sum.minutes %= 60;
      return sum;
    

    } std::string getTime() const; };

MyTime t1(2, 40); MyTime t2(0, 50); cout << (t1 + t2).getTime() << endl;

If one operand is not MyTime, and is an `int`
```cpp
MyTime t1(2, 40);
MyTime t2 = t1 + 20;

可以对重载函数进行修改

MyTime operator+(int m) const
{
    MyTime sum;
    sum.minutes = this->minutes + m;
    sum.hours = this->hours;
    sum.hours += sum.minutes / 60;
    sum.minutes %= 60;
    return sum;
}

We can even support the following operation to be more user friendly
字符串类型

MyTime t1(2, 40);
MyTime t2 = t1 + "one hour";
MyTime operator+(const std::string str) const
{
    MyTime sum = *this;
    if(str=="one hour")
        sum.hours = this->hours + 1;
    else
        std::cerr<< "Only \"one hour\" is supported." << std::endl;
    return sum;
}

Overloaded operators is more user-friendly than functions.

t1 + 20; //operator
t1.operator+(20); // equivalent function invoking

但是,如果是 20 + t1 怎么办?20是基本数据类型,不是函数,不能做运算符重载