【问题标题】:Protected within this context c++在此上下文中受保护 c++
【发布时间】:2020-05-20 20:52:31
【问题描述】:

我猜我遇到了继承问题。

这是头文件中的类:

class Single : public Combination{
public:
    Single(Card* card);
};

这是在 .cpp 文件中初始化的组合:

Combination::Combination(Card** cards, CombinationType type, int numberOfCards){
    this->cards = cards;
    this->numberOfCards = numberOfCards;
    this->type = type;
}

这是 .cpp 文件中的 Single 类,是给我错误的类:

Single::Single(Card* card){
    cards = new Card*[1];
    cards[0] = card;
    Combination(cards, SINGLE, 1); //<- this context
}

错误提示:'Combination::Combination(Card**, CombinationType, int)' 在此上下文中受到保护,但是从头文件中 Single 不能访问 Combination?

编辑:感谢你们快速而翔实的回复!不幸的是,我只能勾选你们中的一个,但我真的很感激!

【问题讨论】:

    标签: c++


    【解决方案1】:

    我猜你想为你的子对象调用基本构造函数。你这样做的方式是使用字段初始化列表:

    Single::Single(Card* card)
        : Combination(new Card*[1], SINGLE, 1) {
        cards = Combination::cards;
        cards[0] = card;
    }
    

    请注意,我也做了一些改动。

    我正在向Combination 构造函数传递一个新的Card 指针数组地址,然后将子cards 成员分配给我们刚刚传递的那个指针(通过从父cards 成员中获取它)。

    【讨论】:

      【解决方案2】:

      您不能像您尝试做的那样从派生类的构造函数体内调用基类的构造函数。它只能从成员初始化列表中调用。因此,您将不得不改变分配数组的方式,例如:

      class Single : public Combination{
      private:
          Card* myCards[1];
      public:
          Single(Card* card);
      };
      
      Single::Single(Card* card)
          : Combination(myCards, SINGLE, 1)
      {
          myCards[0] = card;
      }
      

      或者:

      class Single : public Combination{
      private:
          Card* myCard;
      public:
          Single(Card* card);
      };
      
      Single::Single(Card* card)
          : Combination(&myCard, SINGLE, 1)
      {
          myCard = card;
      }
      

      如果必须在调用基类构造函数之前动态分配数组,则可以使用帮助器,例如:

      class Single : public Combination{
      public:
          Single(Card* card);
      };
      
      Card** CreateCardArray(Card* card)
      {
          Card** cards = new Cards*[1];
          cards[0] = card;
          return cards;
      }
      
      Single::Single(Card* card)
          : Combination(CreateCardArray(card), SINGLE, 1)
      {
      }
      

      或者,您可以简单地执行此操作,假设 Combination::cards 不是 Combination 中的 private,因此 Single 并非无法访问:

      Single::Single(Card* card)
          : Combination(new Cards*[1], SINGLE, 1)
      {
          Combination::cards[0] = card;
      }
      

      或者,您可以直接在new[]语句中指定输入card

      Single::Single(Card* card)
          : Combination(new Cards*[]{card}, SINGLE, 1)
      {
      }
      

      【讨论】:

        猜你喜欢
        • 2020-10-31
        • 2013-04-27
        • 2011-02-05
        • 2023-04-05
        • 1970-01-01
        • 2015-10-02
        • 1970-01-01
        • 1970-01-01
        • 2011-03-04
        相关资源
        最近更新 更多