嘻唰唰第五批之三 抽象基类

问题及代码

 

#include <iostream>
#include<iomanip>
using namespace std;
class Shape
{
public:
    virtual void area() {}
};
class Rectangle:public Shape
{
    float a,b;
public:
    Rectangle(double i,double j):a(i),b(j) {}
    friend Shape printArea(Shape&p);
    void area()
    {
        cout<<a*b<<endl;
    }
};
class Circle:public Shape
{
    float r;
public:
    Circle(float i):r(i) {}
    friend Shape printArea(Shape&p);
    void area()
    {
        cout<<3.1415926*r*r<<endl;
    }
};
class Triangle:public Shape
{
    float w,h;
public:
    Triangle(double i,double j):w(i),h(j) {}
    friend Shape printArea(Shape&p);
    void area()
    {
        cout<<w*h/2<<endl;
    }
};
Shape printArea(Shape &p)
{
    p.area();
}
int main()
{
    float r,a,b,w,h;
    cout<<fixed<<setprecision(2);
    cin>>r;
    Circle circle(r);
    cout<<"area of circle = ";
    printArea(circle);
    cin>>a>>b;
    Rectangle rectangle(a,b);
    cout<<"area of rectangle = ";
    printArea(rectangle);
    cin>>w>>h;
    Triangle triangle(w,h);
    cout<<"area of triangle = ";
    printArea(triangle);
    return 0;
}


可使用指针做形参为什么就错了呢??

还好最后我灵机一动用了引用一试,嘿,对了。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值