基类指针,调到各自的版本
(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)
#include <iostream>
struct Shape {
virtual int area() const { return 0; }
virtual ~Shape() = default;
};
struct Rect : Shape {
Rect(int w, int h) : w_(w), h_(h) {}
int area() const override { return w_ * h_; }
private:
int w_, h_;
};
struct Square : Shape {
explicit Square(int s) : s_(s) {}
int area() const override { return s_ * s_; }
private:
int s_;
};
int main() {
Rect r(3, 4);
Square q(5);
/* 基类指针,调到的是各自的版本 */
const Shape *ps[2] = {&r, &q};
int total = 0;
for (const Shape *p : ps) total += p->area();
std::cout << r.area() << "/" << q.area() << "/" << total << "\n";
return 0;
}
全部评论