为什么我需要通过指向其基类的指针引用继承类的对象,当我意识到对继承类独有的函数调用会产生编译时错误?
为何选择多态?
编辑:
以下是一小段代码:
enum Suit { Spade, Heart, Club, Diamond };
enum Val { Ace=1, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King };
class Card {
private:
Val val;
Suit suit;
public:
Card(Val val, Suit suit) : val(val), suit(suit) {
cout << "Card constructor called" << endl;
}
int get_val() { return val; }
Suit get_suit() { return suit; }
};
class BlackJackCard : public Card {
public:
int garbage;
BlackJackCard(Val val, Suit suit) : Card(val, suit), garbage(9) {}
int get_val() {
Val tmpVal = (Val)Card::get_val();
if(tmpVal == 1) return 11;
if(tmpVal < 10) return tmpVal;
return 10;
}
int exclusive_to_BJC() {
cout << "I do nothing!! and the garbage value my object holds is " << garbage << endl;
}
};
int main() {
Card *newCard = new BlackJackCard(King,Spade);
cout << newCard->get_val() << endl; // 13
cout << newCard->get_suit() << endl; // 0
/*Why should I use a base class referencing if I can't access all the*/
/*members of the object I have constructed(except for the virtual functions).*/
// cout << newCard->exclusive_to_BJC() << endl;
// cout << newCard->garbage << endl;
BlackJackCard *new_bjCard = new BlackJackCard(King,Spade);
cout << new_bjCard->get_val() << endl; // 10
cout << new_bjCard->get_suit() << endl; // 0
cout << new_bjCard->exclusive_to_BJC() << endl;
}
答案 0 :(得分:0)
主要是出于这个原因(点击链接):low coupling。
如果你谈论指针,我理解C ++,所以你也可以看看这个explained example。
答案 1 :(得分:0)
您不需要,可以。事实上,绝大多数时候,最好利用这种可能性,获得更好的代码。考虑:
class Vehicle
{
};
class Car : public Vehicle
{
};
int f(Vehicle *)
{
// code written here will be able to work on any type of vehicle.
}
OOP 允许以f()的方式编写f(),以便以相同的方式处理所有车辆。事实上,Car可以为Vehicle的功能提供专门的功能,而f()甚至不需要知道。