An odd C++ error: test.cpp:15: error: passing ‘const *’ as ‘this’ argument of ‘*’ discards qualifiers

前端 未结 5 730
闹比i
闹比i 2020-12-23 21:13

I\'m having some trouble with a particular piece of code, if anyone can enlighten me on this matter it would be greatly appreciated, I\'ve isolated the problem down in the f

5条回答
  •  甜味超标
    2020-12-23 22:17

    Because of the definition of the member function test1:

    int testing::test1(const testing& test2){
       test2.test();
       return 1;
    }
    

    You are passing in a const reference of for the variable test2.

    That means that you cannot modify any member of test2 and you cannot call any member function that is not const or is not static.

    Here is how you can fix:

    int testing::test() const {
       return 1;
    }
    

    The extra const at the end tells the compiler that you are not planning on modifying the content of the current object (and if you do you will get a different compiling error).

提交回复
热议问题