在这里插入代码片
#include <iostream>
#include <math.h>
#include <memory>
using namespace std;
class RoundPeg {
public:
virtual double getRadius() const = 0;
};
class ConcreteRoundPeg : public RoundPeg {
private:
double radius;
public:
ConcreteRoundPeg(double r) : radius(r) {}
double getRadius() const override { return this->radius; }
};
class RoundHole {
private:
double radius;
public:
explicit RoundHole(double rad) : radius(rad) {}
bool fits(const RoundPeg &peg) const {
return (peg.getRadius() * 2 <= this->radius);
}
};
class SquarePeg {
protected:
double width_;
public:
explicit SquarePeg(double w) : width_(w) {}
[[nodiscard]] inline double getWidth() const noexcept { return this->width_; }
};
class SquarePegAdapter final : public RoundPeg {
private:
std::unique_ptr<SquarePeg> square_;
public:
explicit SquarePegAdapter(std::unique_ptr<SquarePeg> &sp)
: square_{std::move(sp)} {}
double getRadius() const override {
return sqrt(pow(this->square_->getWidth(), 2) + pow(this->square_->getWidth() / 2., 2)) / 2.;
}
};
int main() {
auto h = new RoundHole(10.);
auto p = make_unique<ConcreteRoundPeg>(5.);
if (h->fits(*p)) {
cout << "圆形钉可以插入:" << endl;
} else {
cout << "圆形钉无法插入。" << endl;
}
auto s = make_unique<SquarePeg>(8);
auto sa = new SquarePegAdapter(s);
if (h->fits(*sa)) {
cout << "适配后的方形钉可以插入。" << endl;
} else {
cout << "即使进行了适配,方形钉仍无法插入。" << endl;
}
delete h;
delete sa;
return 0;
}