【问题标题】:Passing a Derived class reference to a function through a Base Class Pointer通过基类指针将派生类引用传递给函数
【发布时间】:2014-04-18 20:01:06
【问题描述】:

我很确定这是 OOP 101(也许是 102?),但我在理解如何处理这个问题时遇到了一些麻烦。

我试图在我的项目中使用一个函数来根据传递给它的对象产生不同的结果。从我今天读到的内容,我相信我有答案,但我希望这里有人可以让我确信一点。

//Base Class "A"
class A
{
    virtual void DoThis() = 0; //derived classes have their own version
};

//Derived Class "B"
class B : public A
{
    void DoThis() //Meant to perform differently based on which
                  //derived class it comes from
};

void DoStuff(A *ref) //in game function that calls the DoThis function of
{ref->DoThis();}     //which even object is passed to it.
                     //Should be a reference to the base class

int main()
{
    B b;

    DoStuff(&b);     //passing a reference to a derived class to call
                     //b's DoThis function
}

有了这个,如果我有多个从 Base 派生的类,我是否能够将任何 Derived 类传递给 DoStuff(A *ref) 函数并利用来自 base 的虚拟?

我这样做是正确的还是离基地很远?

【问题讨论】:

  • 为什么不运行代码,看看能得到什么?
  • @taocp 很乐意,但我正在工作过夜。奇怪的是,我在没有可用 IDE 的情况下完成了大部分编程。
  • 我建议你先看看 C++ 中的虚函数和继承。您当前的代码中存在一些错误。
  • 表明 IDE 大多是包袱……使用 CLI ;-)
  • 如果您可以访问互联网,请尝试使用在线 IDE,例如 ideone.com

标签: c++ oop inheritance polymorphism


【解决方案1】:

所以,使用 Maxim 与我分享的 IDEOne(非常感谢),我能够确认我这样做是正确的

#include <iostream>
using namespace std;

class Character 
{
public:
    virtual void DrawCard() = 0;    
};

class Player: public Character
{
public:
    void DrawCard(){cout<<"Hello"<<endl;}
};

class Enemy: public Character
{
public:
    void DrawCard(){cout<<"World"<<endl;}
};

void Print(Character *ref){
    ref->DrawCard();
}

int main() {

    Player player;
    Enemy enemy;

    Print(&player);

    return 0;
}

Print(&amp;player)Print(&amp;enemy) 确实像我希望的那样调用了它们各自的 DrawCard() 函数。这无疑为我打开了一些大门。感谢那些帮助过的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2016-10-06
    • 2010-12-24
    • 2012-12-26
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多