【问题标题】:How to have virtual functions that returns different types based on the class to which it belongs without including dummy implementation in Base?如何让虚函数根据它所属的类返回不同类型,而不在 Base 中包含虚拟实现?
【发布时间】:2024-04-15 20:40:01
【问题描述】:

我需要一个类层次结构,其中派生类将实现一个返回类型不同的虚函数。我该怎么做。我尝试的是以下代码:

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();
}

我在想如果它可以这样工作,用户只需要将对象等同于一个有效的变量。有没有办法在不包括 Base 中的所有转换运算符的情况下使用一些虚拟实现?

【问题讨论】:

    标签: c++ virtual return-type conversion-operator


    【解决方案1】:

    我想有一个问题,如果它是一个纯虚函数,你不能创建类基的对象。但另一方面,要解决您的问题,您可以尝试使用模板,如下所示。

    #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;
    } 
    

    【讨论】:

    • 感谢您的回复。但我不明白这段代码是如何工作的。 pA->show() 如何链接到 Base::show?由于模板是编译时不应该指向 A obj 吗?当它用于我的代码时,是不是应该写 Factory()() 来获取 int 和 Factory()() 来获取字符串?
    最近更新 更多