簡體   English   中英

奇怪的C ++錯誤:test.cpp:15:錯誤:將'const *'作為'*'的'this'參數傳遞丟棄限定符

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

我在使用特定的代碼時遇到了一些問題,如果有人能夠就此問題啟發我,我將非常感激,我已經在以下示例中將問題分離出來:

#include <iostream>

using namespace std;

class testing{
   int test();
   int test1(const testing& test2);
};

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

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

那么可能導致以下錯誤:

test.cpp:15:錯誤:將'const testing'作為'int testing :: test()'的'this'參數傳遞,丟棄限定符

非常感謝!

問題是從test2.test() testing::test1調用const對象test2上的非const函數test2.test()

testing::test1test2作為參數const testing &test2 所以在testing::test1test2const 然后在函數的第一行:

test2.test()

testing::test函數在test2上調用。 該函數未在簽名端使用const聲明,因此它可能會修改它所調用的對象( this指針隱式傳遞給它),即使它沒有,編譯器也會這樣做。 通過讓你在那里調用它,編譯器可以讓你修改一個const變量而不需要顯式轉換,而C ++不允許這樣做。 因此要解釋錯誤消息

test.cpp:15: error: passing ‘const testing’ as ‘this’ argument of ‘int testing::test()’ discards qualifiers

this指的是成員函數( testing::test )操作的對象,在這種情況下它不是const ,因為testing::test沒有用const聲明,因此在嘗試創建非執行時檢測到不匹配const指針( this )引用const對象( testing ),忽略const 限定符

要解決這個問題 ,請確定testing::test函數是否需要修改它所調用的對象(現在它的編寫方式不是這樣,因為它只return 1 ,但是可能會改變,所以你需要思考它的預期功能是什么)。 如果它應該,那么顯然在const對象上調用它是不好的,雖然你可以使用const_cast來要求編譯器覆蓋它,但這很危險。 如果它不應該,那么將它標記為const ,以便它也可以在const對象上調用:

class testing{
    int test1() const;
    // ...
}

int testing::test() const {
    // ...
}

由於成員函數test1的定義:

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

您正在傳遞變量test2的const引用。

這意味着您無法修改test2的任何成員,也無法調用任何非const或非靜態的成員函數。

以下是您可以修復的方法:

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

最后的額外const告訴編譯器您沒有計划修改當前對象的內容(如果這樣做,您將得到不同的編譯錯誤)。

這一行:test2.test()

調用非const函數,即使test2是const引用。 那就是問題所在。 您可以通過使tests :: test一個const函數來解決這個問題。

testing :: test1(const testing&test2)期望傳遞的對象是const,如果你修改它的變量值,或者訪問未明確定義為const的任何方法,它會給你一個錯誤。

由於test()方法實際上並未更改任何數據,因此最佳做法是將其設置為const,如下所示:

class testing{
   int test() const;
   int test1(const testing& test2);
};

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

或者,在為test1()定義參數時,只需刪除單詞const,它將允許您在閑暇時訪問任何傳遞的對象的方法。

對於快速而簡單的解決方案,請嘗試使用編譯器本身經常建議的-fpermissive進行編譯(這可能是VisualStudio編譯器所做的,因為Windows用戶很少報告此問題)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM