有一个图形由一个圆和一个矩形构成,要求利用面向对象编程计算图形的面积。(圆半径 r=10, 矩形 长=20, 宽=50,求总面积)
图形Graph 圆形Circle矩形Rectangle
半径 radius;长度length; 宽度width
方法1:利用组合(聚合)
#define PI 3.14
#include<iostream>
using namespace std;
class Graph
{
double radius, length, width;
circle c;
Rectangle rec;
public:
Graph(double r,double l,double w)
{
radius = r; length = l; width = w;
}
void S(circle c, Rectangle rec)
{
double sarea;
sarea = c.carea(radius) + rec.recarea(length,width);
cout << sarea << endl;
}
};
class circle
{
public:
double carea(double radius)
{
double s;
s = PI*radius*radius;
return s;
}
};
class Rectangle
{
public:
double recarea(double length,double width)
{
double s;
s = length*width;
return s;
}
};
void main()
{
double radius, length, width;
cout << “请输入圆的半径:”;
cin >> radius;
cout << “请输入长方形的长和宽:”;
cin >> length >> width;
Graph G;
Rectangle rec;
circle c;
G.S(c,rec);
system(“pause”);
}
本人这个程序为什么有这么多错?不会用组合,求指点!
图形Graph 圆形Circle矩形Rectangle
半径 radius;长度length; 宽度width
方法1:利用组合(聚合)
#define PI 3.14
#include<iostream>
using namespace std;
class Graph
{
double radius, length, width;
circle c;
Rectangle rec;
public:
Graph(double r,double l,double w)
{
radius = r; length = l; width = w;
}
void S(circle c, Rectangle rec)
{
double sarea;
sarea = c.carea(radius) + rec.recarea(length,width);
cout << sarea << endl;
}
};
class circle
{
public:
double carea(double radius)
{
double s;
s = PI*radius*radius;
return s;
}
};
class Rectangle
{
public:
double recarea(double length,double width)
{
double s;
s = length*width;
return s;
}
};
void main()
{
double radius, length, width;
cout << “请输入圆的半径:”;
cin >> radius;
cout << “请输入长方形的长和宽:”;
cin >> length >> width;
Graph G;
Rectangle rec;
circle c;
G.S(c,rec);
system(“pause”);
}
本人这个程序为什么有这么多错?不会用组合,求指点!
解决方案
40
两个问题:
1.main函数里Graph G;由于没有默认的无参构造,所以应该改成Graph G(radius, length, width);
2.类的顺序,一定要把circle和Rectangle放到Graph的前面(即使使用class circle;这样的前置声名方法也不行,前置声明只能用于指针参数和指针变量)
1.main函数里Graph G;由于没有默认的无参构造,所以应该改成Graph G(radius, length, width);
2.类的顺序,一定要把circle和Rectangle放到Graph的前面(即使使用class circle;这样的前置声名方法也不行,前置声明只能用于指针参数和指针变量)
#define PI 3.14 #include<iostream> using namespace std; class circle { public: double carea(double radius) { double s; s = PI*radius*radius; return s; } }; class Rectangle { public: double recarea(double length,double width) { double s; s = length*width; return s; } }; class Graph { double radius, length, width; circle c; Rectangle rec; public: Graph(double r,double l,double w) { radius = r; length = l; width = w; } void S(circle c, Rectangle rec) { double sarea; sarea = c.carea(radius) + rec.recarea(length,width); cout << sarea << endl; } }; void main() { double radius, length, width; cout << "请输入圆的半径:"; cin >> radius; cout << "请输入长方形的长和宽:"; cin >> length >> width; Graph G(radius, length, width); Rectangle rec; circle c; G.S(c,rec); system("pause"); }