繁体   English   中英

功能的C ++动态返回类型

[英]c++ dynamic return type for function

我试图有一个泛型类,可以根据对泛型类的输入返回其他类的对象。

从主函数中,如果我将“ 1”作为参数传递给泛型类的构造函数,我希望能够使用getType()获得child1类的对象。 我的问题是:有没有一种方法可以动态地更改getType()的返回类型,或者可以通过其他任何方式来完成此行为?

我当前的实现调用了基类的print()方法,尽管我在通用构造函数中创建了子类的对象,因为m_type是基类。

class base {

    public:
        void print(){
            cout << "base\n";
        }
        virtual ~base() {}
};

class child1 : public base {
    public:
        void print(){
            cout << "child1\n";
        }
};

class child2 : public base {
    public:
        void print(){
            cout << "child2\n";
        }
        void hello(){
            cout << "hello from child 2\n";
        }
};

class generic{

    public:
        generic(int b){
            if(b==1) {
                m_type = new child1();
            }
            else if(b==2) 
                m_type = new child2();
        }

    // Somehow return the object of one of the child class based on input 
    // to constructor.
    base *getType(){
        return m_type;
    }

    base *m_type;
};

int main()
{
    generic *g1 = new generic(1);
    // call the method from child1 class instead of base class.
    g1->getType()->print();
    return 0;
}

print在虚拟base

非虚方法不会表现多态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM