开发者

C++ inheritance - invalid initialization of reference type

I wrote the following code:

class DoubleClass;
class IntClass;

class Number {
public:
    virtual Number& addInt(IntClass& x)=0;
    virtual Number& addDouble(DoubleClass& x)=0;
    virtual Number& operator+(Number& x) = 0;
};

class IntClass : public Number {
private:
    int num;
public:
    IntClass(int num) : num(num) { }
    Number& addInt(IntClass& x) { return x; }
    **Number& addDouble(DoubleClass& x) { return x; }**
    Number& operator+(Number& x) { return x; }
};

class DoubleClass: public Number {
private:
    double num;
public:
    DoubleClass(double num) : num(num) {}
    double get_number() { return num; }
    Number& addInt(IntClass& x) {
        return x;
    }
    Numb开发者_运维百科er& addDouble(DoubleClass& x) { return x; }
    Number& operator+(Number& x) { return x; }
};

Thanks Diego Sevilla, I did what you said and it worked. One more question, I'm supposed to write the function: Number& add(Number& x,Number& y) Is the only way of implementing it is to do dynamic_cast for x and y for all possibilities (casting x and y to int, and if an exception is thrown then casting x to double and y to double, and so on), or is there an easier way?


At that point the compiler doesn't know DoubleClass inherits from Number. You should separate class declaration from method implementation. For example:

class IntClass : public Number {
// ...

  Number& addDouble(DoubleClass& x); // Note: no implementation
};

class DoubleClass : public Number
{
// ...
};

inline Number& IntClass::addDouble(DoubleClass& x) { return x; } // Won't fail now


You haven't defined DoubleClass, so you can't do anything with the reference other than take the address of the object and pass it around.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜