Function overloading
cv::Mat是opencv中最基础的数据类型,表示一个矩阵
Mat add(Mat& A, Mat& B);Mat add(Mat& A, float b);Mat add(float a, Mat& B);Mat mul(Mat& A, Mat& B);Mat mul(Mat& A, float b);Mat mul(float a, Mat& B);...
一系列函数有相同的函数名,但是函数列表不同,就叫做函数的重载。
More convenient to code as follows
Mat A, B;float a, b;//…Mat C = A + B;Mat D = A * B;Mat E = a * A;
#include <iostream>#include <opencv2/opencv.hpp>using namespace std;int main(){float a[6]={1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f};float b[6]={1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f};cv::Mat A(2, 3, CV_32FC1, a);cv::Mat B(3, 2, CV_32FC1, b);cv::Mat C = A * B;cout << "Matrix C = " << endl<< C << endl;return 0;}
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!");
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是基本数据类型,不是函数,不能做运算符重载
