Why does the function parameter const cv::Mat &img fail? Still can modify const object content?

1. Examples are as follows:

bool MainWindow::readImage(const QString &path)
{
    cv::Mat img = cv::imread(path.toStdString());
    cv::imwrite("d:\\src.jpg", img);
    test(img);
    cv::imwrite("d:\\dst.jpg", img);

    return true;
}

void MainWindow::test(const cv::Mat &img)
{
    cv::cvtColor(img, img, cv::COLOR_BGR2RGB);
}

The source code compilation can pass normally.

Finally, the function void test(const cv::Mat &img) is executed, the value of the const object img is changed, and the BGR channel is changed to RGB.

why?help me!

2. Similarly, C++ follows this format and writes as follows:

class CHello
{
public:
    int a = 0;
};

void calc(const CHello &h1, CHello &h2)
{
    h2.a = h1.a + 10;
}

void test(const CHello &h)
{
    calc(h, h);
}

int main(int argc, char *argv[])
{
    CHello h;
    h.a = 20;
    test(h);

    return 0;
}

An error will occur when compiling the source code, prompting:

C:\Users\xxx\Downloads\untitled\main.cpp:16: error: C2664: “void calc(const CHello &,CHello &)”: cannot convert argument 2 from “const CHello” to “CHello &”
. .\untitled\main.cpp(16): error C2664: “void calc(const CHello &,CHello &)” : cannot convert argument 2 from “const CHello” to “CHello &” ..\untitled\
main.cpp (16): note: conversion loses qualifier
..\untitled\main.cpp(9): note: see declaration of "calc"

---

Recommended reading:

Do you really understand the difference between cv::Mat, const cv::Mat, const cv::Mat&, cv::Mat&? _A cute blog that is not cute at all-CSDN blog

 

Guess you like

Origin blog.csdn.net/libaineu2004/article/details/130123271