【问题标题】:No matching function for call in constructor - C++ 11构造函数中没有匹配的调用函数 - C++ 11
【发布时间】: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"

但他们似乎都没有处理我的问题(将另一个类的数组传递给这个类)。

【问题讨论】:

标签: c++ arrays oop c++11 constructor


【解决方案1】:

C++ 有 std::array,您包含但未使用。 您可以将构造函数更改为:

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

直播godbolt


这是错误的:

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

它正在访问 cards 的第 6 个元素,该元素不存在并导致 undefined behavior

【讨论】:

  • 这就是我的本意。我忘记了古老数组和std::array 之间的 C++ 区别
  • @JerryM。我还以为你把它误认为是 C 数组了。
猜你喜欢
  • 2013-10-31
  • 2015-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-23
  • 1970-01-01
  • 2022-01-15
相关资源
最近更新 更多