我正在尝试实现接下来的2个功能

Number& DoubleClass::operator+( Number& x);
Number& IntClass::operator+(Number& x);

我不确定该怎么做..(它们的单向性在下面说明):
   class IntClass;
   class DoubleClass;

class Number {
        //return a Number object that's the results of x+this, when x is either
        //IntClass or DoubleClass
        virtual Number& operator+(Number& x) = 0;
};


class IntClass : public Number {
    private:
        int my_number;
        //return a Number object that's the result of x+this.
        //The actual class of the returned object depends on x.
        //If x is IntClass, then the result if IntClass.
        //If x is DoubleClass, then the results is DoubleClass.
    public:
        Number& operator+(Number& x);
};


class DoubleClass : public Number {
    private:
        double my_number;
    public:

        //return a DoubleClass object that's the result of x+this.
        //This should work if x is either IntClass or DoubleClass
        Number& operator+( Number& x);
};

最佳答案

您需要将多态与返回的类型分开。您可以使用封装来实现。

例如:

class Number
{
    class NumberImpl
    {
    public:
        virtual ~NumberImpl(){}
        virtual NumberImpl* add(Number x) const = 0;
    };
    class IntClass;
    class DoubleClass;

    auto_ptr<NumberImpl> pimpl;
    Number(NumberImpl* p) : pimpl(p) {}

    //return a Number object that's the results of x+this, when x is either
    //IntClass or DoubleClass
public:
    Number operator+( const Number& x ) const { return Number(pimpl->add(x)); }
};


class Number::IntImpl : public Number::NumberImpl
{
private:
    int my_number;
public:
    //return a Number object that's the result of x+this.
    //The actual class of the returned object depends on x.
    //If x is IntImpl, then the result is new IntImpl.
    //If x is DoubleImpl, then the results is new DoubleImpl.
    virtual NumberImpl* add(Number& x) const;
};

class Number::DoubleImpl : public Number::NumberImpl
{
private:
    double my_number;
public:
    //return a new DoubleImpl object that's the result of x+this.
    //This should work if x is either IntImplor DoubleImpl
    virtual NumberImpl* add(Number& x) const;
};

关于c++ - C++中的多态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4651032/

10-13 07:04