如何在向量上调用不同的重写方法

How to call different overridden methods on a vector

本文关键字:重写 方法 调用 向量      更新时间:2023-10-16

我第一次在 C++ 中使用 vector,我的问题是调用不同的重写方法,让我解释一下:我得到了 SPECIALCARD 子类化的 CARD。在 CARD 中有一个方法 printCard(),在 SPECIALCARD 中,该方法被覆盖。然后主要我创建一个卡的向量。我在第一个位置放了一张卡,在第二个位置放了一张特殊卡。当我尝试在第一个和第二个位置调用 printCard() 方法时,它总是运行父方法(但我想在第一个位置调用父方法,在第二个位置调用 son 方法)。这是卡类:

CARD.H
using namespace std;
class Card
{
    public:
        Card(int number, string seed);
        virtual void printCard();
    protected:
        int number;
        string seed;
};
CARD.CPP
#include "Card.h"
#include <iostream>
#include <string>
using namespace std;
Card::Card(int number, string seed)
{
   this->number = number;
   this->seed = seed;
}
void Card::printCard()
{
    cout << "the card is " << number << " of " << seed << endl; 
}

这是特殊卡类

SPECIALCARD.H
#include "Card.h"
#include <string>
using namespace std;
class Special_Card : public Card
{
    public:
        Special_Card(int number, string name, string seed);
        string getName();
        virtual void printCard();
    private:
        string name;
};
SPECIALCARD.CPP
#include <iostream>
#include "Special_Card.h"
#include "Card.h"
#include <string>
using namespace std;
Special_Card::Special_Card(int number, string name, string seed): Card(number, seed)
{
    this->number = number;
    this->name = name;
    this->seed = seed;
}
//overridden method
void Special_Card::printCard()
{
    cout << "the card is " << name << " of " << seed << endl;
}

最后,我们得到了我创建矢量的主要内容

#include <iostream>
#include "Card.h"
#include "Special_Card.h"
#include <string>
#include <vector>
using namespace std;
int main()
{
    vector <Card> deck;
    deck.push_back(Card(1,"hearts"));
    deck.push_back(Special_Card(10,"J","hearts"));
    deck[0].printCard();
    deck[1].printCard();
}

控制台输出为这张牌是1红心/n这张卡是 10 颗红心(在第二秒我想打印"这张卡是 J 颗红心")

您在main中的代码将导致对象切片。要获得正确的多态行为,您需要使用指针或引用。

如果您希望您的向量拥有这些对象,那么我会让向量包含std::unique_ptr这将允许包含的对象多态地起作用。

#include <memory>
int main()
{
    std::vector<std::unique_ptr<Card>> deck;
    deck.push_back(std::make_unique<Card>(1,"hearts"));
    deck.push_back(std::make_unique<Special_Card>(10,"J","hearts"));
    deck[0]->printCard();
    deck[1]->printCard();
}

我终于这样解决了: 我使用 Card* 的 e 向量

#include <iostream>
#include "Card.h"
#include "Special_Card.h"
#include <string>
#include <vector>
int main()
{
    vector <Card*> deck;
    deck.push_back(new Card(1,"hearts"));
    deck.push_back(new Special_Card(10,"J","hearts"));
}