【发布时间】:2020-01-22 09:03:30
【问题描述】:
我正在尝试创建两个类:一个用于 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() 的信息,但我不打算空白地实例化它。我将创建五张卡片,然后将五张卡片分配给一个班级。比如:
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"
但他们似乎都没有处理我的问题(将另一个类的数组传递给这个类)。
【问题讨论】:
-
还要注意arrays are not passed by value to functions、
Cards card[5]与Cards* card相同。您可能应该改用std::array,它可以按您的意愿工作。 -
this->cards[5] = ...写入不存在的数组元素。cards的有效索引为 0 到 4。 -
我知道索引 0->4,因为数组是基于 0 的,不像 MATLAB,但我想说的是大小为 5。
标签: c++ arrays oop c++11 constructor