创建函数接受基类指针,但调用派生类函数 [英] Create Function taking base class pointer but calling derived class function

查看:139
本文介绍了创建函数接受基类指针,但调用派生类函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类 A (base)和 B (从 / code>):

I have two classes A (base) and B (deriving from A):

class A { };

class B : public A
{
    int data;
public:
    int get_data() { return data; }
};

现在我有一个函数测试,它接受基类指针和调用派生类函数:

Now I have a function test which takes base class pointer and calls derived class function :

void test(A * ptr)
{
    ptr->get_data();
}

但问题是 ptr 可以指向 A 的对象或 B 的对象。如果它指向 B 的对象,那么OK,但如果到 A 的对象,那么它是一个问题。

But problem is ptr may point to A's object or B's object. If it points to B's object, then OK, but if to A's object, then it is a problem.

此外,我不想让 get_data() virtual,因为 data 不是 A 的对象的属性。

Moreover, I don't want to make get_data() virtual because data is not property of A's object.

如何检查 ptr 是否指向 B 的对象?我可以认为的一个解决方案是 dynamic_cast 并检查 NULL

How can I check if ptr points to B's object? One solution which I can think is dynamic_cast and check it for NULL. Is it the best solution or can I have a better solution ?

推荐答案

如果你可以改变 A B (包括添加虚拟函数),如果可以重新洗牌 code>函数可以使用访问者模式。下面是一个使用更好的名为 Base 派生类的示例:

If you can change the interface of A and B (including adding virtual functions) and if you can re-shuffle the code in the test function you can use the "visitor pattern". Here's a sample using the better named Base and Derived classes:

class Visitor
{
public:
    void Visit(Base * B)
    {
    }

    void Visit(Derived * D)
    {
        int data = D->get_data();
    }
};

class Base
{
public:
    virtual void Accept(Visitor * V )
    {
        V->Visit(this);
    }
};

class Derived: public Base
{
public:
    int get_data()
    {
        return data;
    }

    virtual void Accept(Visitor * V )
    {
        V->Visit(this);
    }
private:
    int data;
};

这样你可以遍历 Base * ,调用接受每个元素,并知道只有 Derived 元素 get_data 方法将被调用。

This way you can iterate over your vector of Base*, call Accept of each element and know that only for Derived elements the get_data method will be called.

这篇关于创建函数接受基类指针,但调用派生类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆