[英]C++ using object of a class declared after
for some reason i have to declare multiple classes in the same file, and in paricoular I have to use an object of one of these classes before declaring, here is an example: 由于某种原因,我必须在同一文件中声明多个类,并且在声明中,我必须在声明之前使用这些类之一的对象,这是一个示例:
#include<iostream>
using namespace std;
class square{
double side;
double area;
square(double s){
side = s;
}
void calcArea(){
area = side*side;
}
void example(){
triangle t(2.3,4.5);
t.calcArea();
}
};
class triangle{
double base;
double height;
double area;
triangle(double s,double h){
base = s;
height = h;
}
void calcArea(){
area = (base*height)/2;
}
};
int main(){
}
You can see that in example() method in square class, I use an object belonging to class triangle that is declared after its use. 您可以看到,在正方形类的example()方法中,我使用了一个属于三角形类的对象,该对象在使用后声明。 There's a way in order to let work this pieces of code? 有一种方法可以使这段代码起作用?
Since square
needs triangle
, but triangle
doesn't need square
, you can simply change the order of the class definitions: 由于square
需要triangle
,但是triangle
不需要square
,您可以简单地更改类定义的顺序:
class triangle {
// ...
};
class square {
// ...
};
Or, since example
is the only thing in square
that needs triangle
, define example
after the definition of triangle
: 或者,因为example
是唯一square
需要triangle
,定义example
的定义后triangle
:
class square {
// ...
void example();
};
class triangle {
// ...
};
void square::example() {
triangle t(2.3,4.5);
t.calcArea();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.