将子类作为构造函数中的参数传递

时间:2017-02-19 17:59:41

标签: c++ inheritance polymorphism

我是c ++的新手,我试图创建一个带有RoleCard参数的Player实例。我希望能够在Driver.cpp中传递继承RoleCard的MedicCard。但是,我似乎无法找到正确的方法来做到这一点。我的目标是能够动态更改变量roleCard以创建新的Player实例。

Driver.cpp

RoleCard roleCard;
MedicCard medicCard;    
roleCard = medicCard;

Player demoPlayer(roleCard);

Player.h

#pragma once
#include "RoleCard.h"
#include <string>
#include <vector>

class Player
    {
    public:
        Player();
        Player( RoleCard rolecard );            
    };

Player.cpp

#include "stdafx.h"
#include "Player.h"
#include<string>

using namespace std;

Player::Player()
{
}

Player::Player(RoleCard roleCard)
{    
}

RoleCard.h

#pragma once

class RoleCard
{
public:
    RoleCard();
};

class MedicCard: public RoleCard
{
public:
    MedicCard();
};

RoleCard.cpp

#include "stdafx.h"
#include "RoleCard.h"

using namespace std;

RoleCard::RoleCard()
{    
}
MedicCard::MedicCard()
{    
}

1 个答案:

答案 0 :(得分:0)

当你将派生类的对象分配给像这样的基类对象时

RoleCard roleCard;
MedicCard medicCard;    
roleCard = medicCard;

派生类中的discard all of the data(也称为切片)。 如果您想要多态行为,请使用对基类的引用或指针:

Player(RoleCard& rolecard);
...
MedicCard medicCard;
Player demoPlayer(medicCard);