簡體   English   中英

沒有匹配的 function 用於在構造函數中調用 - C++ 11

[英]No matching function for call in constructor - C++ 11

我正在嘗試創建兩個類:一個用於卡片,它包含兩個等級和花色字符串,另一個用於手牌 class,它包含一個大小為 5 的卡片對象數組。

#include <iostream>
#include <array>
#include <string>

using namespace std;

class Card
{

    public:
    explicit Card(string rank, string suit){
        this->rank = rank;
        this->suit = suit;
    }

    string getRank(){
        return rank;
    }

    string getSuit(){
        return suit;
    }

    protected:
    string rank;
    string suit;

}; 

class Hand
{
    public:
    explicit Hand(Card cards[5]){
        this->cards[5] = cards[5];
    }

    protected:
    Card cards[5];
    bool isFlush;
    bool isStraight;
    bool isRoyal;
    bool isPair;
    bool istwoPair;
    bool isTOAK;
    bool isFOAK;
};

嘗試編譯時,我得到:

wip.cpp:33:35: error: no matching function for call to 'Card::Card()'
   33 |     explicit Hand(Card myCards[5]){
      |                                   ^

為什么構造函數會出錯? 我理解No matching function for call to Card::Card()的消息,但我不打算空白地實例化它。 我將創建五張卡,然后將五張卡分配給 class。 就像是:

int main(){
    Card card1("3", "Spade");
    Card card2("3", "Spade");
    Card card3("A", "Diamond");
    Card card4("K", "Heart");    
    Card card5("1", "Spade");

    Card hand1cards[5] {card1, card2, card3, card4, card5};

    Hand myHand(hand1cards);    

}

所以我不打算進行構造函數重載,那為什么會出現這個錯誤呢? 我可以做些什么來修復我的構造函數以允許我傳入固定大小的 Card 對象數組來創建 Hand object?

我查看了其他一些具有類似問題的問題,即:

如何為成員使用非默認構造函數?

錯誤:沒有匹配的 function 用於調用

“錯誤:沒有匹配的 function 用於調用”

然而,他們似乎都沒有解決我的問題(將另一個 class 的數組傳遞給這個類)。

C++ 具有您包含但未使用的std::array 您可以將構造函數更改為:

explicit Hand(array<Card, 5> cards) : cards(cards){}

住在godbolt


這是錯誤的:

this->cards[5] = cards[5];

它正在訪問cards的第 6 個元素,該元素不存在並導致未定義的行為

暫無
暫無

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

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