-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlsp.cpp
More file actions
61 lines (52 loc) · 1.35 KB
/
lsp.cpp
File metadata and controls
61 lines (52 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* The Liskov Substitution Principle
* FUNCTIONS THAT USE POINTERS OR REFERENCES TO BASE
CLASSES MUST BE ABLE TO USE OBJECTS OF DERIVED CLASSES
WITHOUT KNOWING IT.
* In other word, the derive can substitute his parent and behaves the same.
* 子類別必須能夠替換父類別,並且行為正常
*/
#include <cassert>
#include <iostream>
using namespace std;
struct Rectangle {
virtual void setWidth(double w) {
// Design by contract - precondition
auto old = this->height;
this->width = w;
// Deisgn by Contract - postcondition
assert(this->width == w && this->height == old);
}
virtual void setHeight(double h) {
this->height = h;
}
double getHeight() const {return height;}
double getWidth() const {return width;}
double getArea() const {return height*width;}
private:
double height, width;
};
struct Square : Rectangle {
void setWidth(double w) override;
void setHeight(double h) override;
};
void Square::setWidth(double w) {
Rectangle::setWidth(w);
Rectangle::setHeight(w);
}
void Square::setHeight(double h) {
Rectangle::setHeight(h);
Rectangle::setWidth(h);
}
void g(Rectangle& r) {
r.setHeight(5);
r.setWidth(4);
cout << r.getArea() << endl;
assert(20.0 == r.getArea());
}
int main() {
Rectangle r;
g(r);
Square s;
g(s);
}