全部书籍

专业

应用 关于 Coach 登录 开始阅读

书籍暂未推出简体中文版——当前显示英文版。

Computer Science · 术语表

什么是 Virtual function, override?

又称: virtual function · override

Definition 3.3 University Computer Science — Year 2 · 第 3 章 — Inheritance and Polymorphism

A member function declared virtual in a base class is a virtual function. A derived class overrides it by declaring a function with the same name and parameters; the keyword override asks the compiler to check that there is something to override, and final forbids further overriding. A function that is not virtual can only be hidden by a derived function of the same name, which is a different thing.

示例

Example 3.10 (A square that is not a rectangle)

class Rectangle {
public:
    Rectangle(double w, double h) : w_(w), h_(h) {}
    virtual ~Rectangle() = default;
    virtual void set_width(double w) { w_ = w; }    // postcondition: width w, height unchanged
    virtual void set_height(double h) { h_ = h; }   // postcondition: height h, width unchanged
    double area() const { return w_ * h_; }

protected:
    double w_, h_;
};

class Square : public Rectangle {                    // keeps its sides equal
public:
    explicit Square(double s) : Rectangle(s, s) {}
    void set_width(double w) override { w_ = h_ = w; }
    void set_height(double h) override { w_ = h_ = h; }
};

// A client written against Rectangle: resize a plot to 4 m by 5 m.
bool resize_plot(Rectangle &r)
{
    r.set_width(4);
    r.set_height(5);
    return r.area() == 20;                           // what the postconditions promise
}

int main()
{
    Rectangle r(2, 3);
    Square s(3);
    bool ok_r = resize_plot(r), ok_s = resize_plot(s);
    std::printf("rectangle: %s (area %g)\n", ok_r ? "as promised" : "broken", r.area());
    std::printf("square:    %s (area %g)\n", ok_s ? "as promised" : "broken", s.area());
    return 0;
}
Listing 3.9. A client of Rectangle given a Square code/bachelor-2/03-cpp-polymorphism/listings/square.cpp
$ g++ -std=c++20 -O2 -Wall -Wextra -o square square.cpp && ./square
rectangle: as promised (area 20)
square:    broken (area 25)
Output 3.8. The client’s promise holds for one of the two.

resize_plot relies on the postconditions of Rectangle: after set_width(4) and set_height(5) the area is 20. Square must keep its sides equal, so its set_height(5) also changes the width, and the client sees 25. The square of geometry is a rectangle because a geometric rectangle never changes; a mutable Square cannot keep the promises of a mutable Rectangle, whichever way it overrides the setters (Exercise 3.8). Either the two classes have no setters, or Square is not derived from Rectangle.

在原文中阅读 →