有人可以請解釋爲什麼我不能編譯這段代碼?我知道這個設計非常糟糕,但我只想知道爲什麼我不能編譯它,先謝謝 P.S.遺憾的格式,不能在面板上找到反引號在C++上編譯錯誤
//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);
}
};
我有錯誤的IntClass在addDouble方法:
invalid use of undefined type struct DoubleClass
編輯 IntClass不是嵌套類NumberClass
的
你不能打擾包括錯誤? – 2011-01-08 22:16:09
編譯器報告什麼錯誤?在哪一行? – 2011-01-08 22:16:17
修復了格式化;您可以選擇代碼並使用Markdown編輯器工具欄上的「{}」按鈕進行格式化,也可以按Ctrl + K或在每行前加上四個空格。 – 2011-01-08 22:16:58