gpt4 book ai didi

c++ - C++编译错误

转载 作者:行者123 更新时间:2023-11-28 03:53:21 25 4
gpt4 key购买 nike

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

//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 的完整声明之后,或者将您的代码分成头文件和实现文件来解决。

关于c++ - C++编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4636439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com