|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 longdeqidao 于 2012-12-16 21:58 编辑
- //已经习惯类名第一个字母大写,所以改了一下类名
- #include <iostream>
- using namespace std;
- /*
- *这个类中,给的例子中是纯虚函数,但是在主函数中Square s(3);
- *出现了cannot declare variable 's' to be of abstract type 'Square'|的错误
- *所以我改了一下不是纯虚函数,就通过。测试答案是正确的,这点我没有搞懂原因
- *之后我分别改变Area和SetData为虚函数,发现Area为纯虚函数没有错误,而SetData就有
- *所有现在的源代码就是能通过的状态,这一点我没有搞懂。
- *我估计是Square,Circle类中得SetData参数个数与基类不同造成的。望高手解答。
- */
- class Shape
- {
- public:
- virtual float Area() = 0; //纯虚函数
- virtual void SetData(float,float){}; /*非纯虚函数,纯虚函数应为virtual void SetData(float,float) = 0;但出现上述错误*/
- };
- class Triangle: public Shape
- {
- public:
- Triangle(float ww=0,float hh=0) {
- w=ww;
- h=hh;
- }
- virtual float Area() {
- return w*h/2;
- }
- virtual void SetData(float ww,float hh) {
- w=ww;
- h=hh;
- }
- private:
- float w,h;
- };
- class Rectangle: public Shape {
- public:
- Rectangle(float ww, float hh): w(ww), h(hh){}
- virtual float Area() {
- return w * h;
- }
- virtual void SetData(float ww, float hh) {
- w = ww;
- h = hh;
- }
- private:
- float w;
- float h;
- };
- class Square: public Shape {
- public:
- Square(float ss): s(ss){}
- virtual float Area() {
- return s * s;
- }
- void SetData(float ss){ //此处应不需要虚函数,因为函数个数不同
- s = ss;
- }
- private:
- float s;
- };
- class Circle: public Shape {
- public:
- Circle(float rr): r(rr){}
- virtual float Area(){
- return 3.1415 * r * r;
- }
- void SetData(float rr){ //此处应不需要虚函数,因为函数个数不同
- r = rr;
- }
- private:
- float r;
- };
- float CaclArea(Shape *s)
- {
- return s->Area();
- }
- int main()
- {
- Triangle t(2, 4);
- Rectangle r(2, 4);
- Square s(3);
- Circle c(3);
- Shape *pt = &t, *pr = &r;
- Shape *ps = &s, *pc = &c;
- double sum;
- sum = CaclArea(pt) + CaclArea(pr) +
- CaclArea(ps) + CaclArea(pc);
- cout << sum << endl;
- return 0;
- }
复制代码
|
|