我正在尝试创建两个类:一个用于 Card,其中包含两个等级和花色字符串,另一个用于 Hand,其中包含大小为 5 的 Card 对象数组。
#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 对象?
我看过其他一些有类似问题的问题,即:
How do you use the non-default constructor for a member?
error: no matching function for call to
"error: no matching function for call to"
但是他们似乎都没有解决我的问题(将另一个类的数组传递给这个类)。
最佳答案
C++ 有 std::array
你包含但没有使用的。
您可以将构造函数更改为:
explicit Hand(array<Card, 5> cards) : cards(cards){}
住在 godbolt
这是错误的:
this->cards[5] = cards[5];
它正在访问 cards
的第 6 个元素,它不存在并导致 undefined behavior .
关于c++ - 构造函数中没有匹配的调用函数 - C++ 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58043020/