簡體   English   中英

在C ++中發生沒有匹配的函數來調用錯誤

[英]occur no matching function for call to error in c++

我是c++的新手,我知道有很多類似的問題,但不幸的是並沒有幫助我解決這個問題(我認為這是一個概念上的誤解)

所以我有這個constructor

Field::Field(const Position &posG, const Position &posC) {
    //...
}

我正在創建一個Field如下

// Create positions
Position posG, posC;
posG.x = 3;
posG.y = 3;
posC.x = 4;
posC.y = 4;

// Create pointers to positions
const Position *pPosC(&posC);
const Position *pPosG(&posG);

// Create field
Field field (pPosG, pPosC);

位置在哪里

struct Position {
    int x;
    int y;
};

然后我得到這個異常:

main.cpp:27:30: error: no matching function for call to ‘Field::Field(const Position*&, const Position*&)’
     Field Field (pPosG, pPosC);

In file included from main.cpp:2:0:

有什么幫助嗎? 問候

Field(const Position &posG, const Position &posC);
                     ^^^^^                 ^^^^^^

這些是參考。 因此,當您嘗試傳遞指針時

Field field (pPosG, pPosC);
             ^^^^^   ^^^^
             pointer   pointer

它無法編譯。

使構造函數接受引用指針( const Position *&posG)或傳遞指針的值( *pPosG ),或直接傳遞值( posG )。

當您將構造函數定義為

Field(const Position &posG, const Posicion &posC);

您可以將Position類型的對象用作其參數,而不是Position指針。

您可以使用:

Field field(posG, posC);

要么

Field field(*pPosG, *pPosC);

您的構造函數需要引用,而不是指針。

附帶說明一下,不清楚為什么要使用引用或指針。

您必須定義一個constructor ,然后使用const Position *pPosC(&posC); 表達。

您必須像這樣定義constructor-copy

struct Posicion {
public :
    Position(const Position &pos)         // constructor copy
    {
        // some code here
        x = pos.x;
        y = pos.y;
    }

    int x;
    int y;
};

暫無
暫無

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

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