简体   繁体   中英

How to have virtual functions that returns different types based on the class to which it belongs without including dummy implementation in Base?

I need a class hierarchy in which the derived classes will have implementation of a virtual function that differs in the return type. How can i do it. What i have tried is the following code:

using namespace std;
class Base
{
public:
    Base()
    {
        cout<<"Constructor of Base"<<endl;
    }
    virtual Base& Decode()=0;
    virtual operator int(){return -1;}
    virtual operator string(){return "WRONG";}
};
class Der1:public Base
{
    int i;
public:
    Der1(int j=0):Base(),i(j)
    {
        cout<<"COnstructor of Der1"<<endl;
    }
    Base& Decode()
    {
        cout<<"Decode in Der1"<<endl;
        return *this;
    }
    operator int()
    {
        return i;
    }
};
class Der2:public Base
{
    string s;
public:
    Der2(string temp="sajas"):Base(),s(temp)
    {
        cout<<"Constructor of Der2"<<endl;
    }
    Base& Decode()
    {
        cout<<"Decode in Der2"<<endl;
        return *this;
    }
    operator string()
    {
        return s;
    }
};
int main()
{
    Base *p=new Der1();
    int val=p->Decode();
}

I was thinking if it could work this way user would just have to equate the object to a valid variable. Is there any way to do it without including all the conversion operators in Base with some dummy implementatin?

I guess there is one problem, if it is a Pure virtual function you cannot create an object of the class base. But on the other hand to solve your problem you can try out using templates, something like below.

#include <iostream>

class Base{
public:
    Base(){}
    virtual ~Base(){}
    virtual void show() const {
        std::cout << "Base::show()!" << std::endl;
    }
};
class A:public Base{
public:
    A(){}
    virtual ~A(){}
    virtual void show() const{
        std::cout << "A::show()!" << std::endl;
    }
};

template<typename T>
class Factory{
public:
    const T* operator()() const{
        return &t;
    }
private:
    T t;
};

int main(){
    const A* pA = Factory<A>()();
    pA->show();
    Factory<A>()()->show();
    return 0;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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