有人可以解释一下为什么我不能编译这段代码吗?我知道这个设计很糟糕,但是我只想知道为什么我不能编译它,谢谢
附言抱歉,该格式无法在面板上找到反引号

//Deriving classes definition
class IntClass; class DoubleClass;

//The Virtual Number Class. IntClass and FloatClass will derive from this class.

class Number {
    public:
        //return a Number object that's the results of x+this, when x is DoubleClass
        virtual Number& addDouble(DoubleClass& x) = 0;

        //return a Number object that's the results of x+this, when x is IntClass
        virtual Number& addInt(IntClass& x) = 0;

        //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;
    public:
        //Constructor
        IntClass(int n):my_number(n) {}

        //returns the number stored in the object
        int get_number()  {return my_number;}

        //return a DoubleClass object that's the result of x+this
        Number& addDouble(DoubleClass& x){
         return  x.addInt(*this);
        }

        //return an IntClass object that's the result of x+this
        Number& addInt(IntClass& x){
         IntClass* var = new IntClass(my_number + x.get_number());
         return  *var;
        }

        //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.
        Number& operator+(Number& x){
         return x.addInt(*this);
        }
};

class DoubleClass : public Number {
    private:
        double my_number;
    public:
        //Constructor
        DoubleClass(double n):my_number(n) {}

        //returns the number stored in the object
        double get_number()  {return my_number;}

        //return a DoubleClass object that's the result of x+this
        Number& addDouble(DoubleClass& x){
         DoubleClass* var = new DoubleClass(my_number + x.get_number());
         return *var;
        }

        //return a DoubleClass object that's the result of x+this
        Number& addInt(IntClass& x){
         DoubleClass* var = new DoubleClass(my_number + x.get_number());
         return *var;
        }

        //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){
         return x.addDouble(*this);
        }
};


我在addDouble方法的IntClass中出错:

invalid use of undefined type struct DoubleClass


编辑的IntClass不是NumberClass的嵌套类

最佳答案

IntClass::addDouble中,您使用类DoubleClass,但是此时DoubleClass仅具有前向声明,因此无法在其上调用方法。

可以通过将IntClass::addDouble的正文放在class DoubleClass的完整声明之后,或将代码分为头文件和实现文件来解决此问题。

08-06 12:54