题目链接:https://www.nowcoder.com/practice/699ba050e2704591ae3e62401a856b0e?tpId=107&&tqId=33421&rp=1&ru=/ta/beginner-programmers&qru=/ta/beginner-programmers/question-ranking
看了那么多答案,这个应该是最标准的,既用到了初始化列表很高端的写法,又实现了虚函数重写,实现了多态
#include<iostream>
using namespace std;
class shape{
private:
int x;
int y;
public:
shape() : x(0), y(0){ }
shape(int a, int b) : x(a), y(b){ }
virtual void GetArea() = 0;
};
class Circle : public shape{
private:
double radius;
const static double PI;
public:
Circle() : radius(0) { }
Circle(int r) : radius(r) { }
virtual void GetArea(){
double S;
S = PI * radius * radius;
cout << S << endl;
}
};
const double Circle::PI = 3.14;
class Retangle : public shape{
private:
int w;
int h;
public:
Retangle() : w(0), h(0){ }
Retangle(int x, int y) : w(x), h(y){ }
virtual void GetArea(){
double S;
S = w * h;
cout << S << endl;
}
};
class Square : public Retangle{
private:
int a;
public:
Square() : a(0){ }
Square(int x) : a(x){ }
virtual void GetArea(){
double S;
S = a * a;
cout << S << endl;
}
};
int main(){
int a, b, c, d;
cin >> a >> b >> c >> d;
Retangle re(a, b);
Circle C(c);
Square s(d);
shape* p;
p = &re;
p->GetArea();
p = &C;
p->GetArea();
p = &s;
p->GetArea();
return 0;
}

京公网安备 11010502036488号