6

是否可以使用多重继承通过 dynamic_cast 获取对象?由于我的设计问题,我更喜欢跳过作曲技巧。谢谢,

#include <stdio.h>

namespace
{
    template <typename T>
    class Beta
    {
    protected:
        Beta() { printf("Beta\n"); }
    public:
        virtual ~Beta() { printf("~Beta\n"); }
        virtual void Run() = 0;

    };

    class Alpha
    {
    protected:
        Alpha() { printf("Alpha\n"); }
    public:
        virtual ~Alpha() { printf("~Alpha\n"); }
        virtual void Check() = 0;

        template <typename T>
        Beta<T>* GetBeta()
        {
            Beta<T>* b = dynamic_cast< Beta<T>* >(this);

            if(b == NULL) printf("NULL !!\n");

            return b;
        }
    };

    template <typename T>
    class Theta : public Alpha, Beta<T>
    {
    public:

        void Run()
        {
            printf("Run !\n");
        }

        void Check()
        {
            printf("Check !\n");
        }

    };
}

int main(int argc, const char* argv[])
{
    Alpha* alpha = new Theta<int>();
    Beta<int>* beta = alpha->GetBeta<int>();

    alpha->Check();

    if(beta) beta->Run();

    delete alpha;
    return 0;
}

上面代码的结果是

阿尔法贝塔空!!查看 !~Beta~Alpha

4

1 回答 1

8

好吧,如果我更换:

public Alpha, Beta<T>

和:

public Alpha, public Beta<T>

事情会奏效。细节中总有魔鬼...

于 2013-09-18T16:33:24.807 回答