简体   繁体   中英

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;
    }
    Number& 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.

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