This principle means that a subclass should be able to replace its parent class anywhere at any time without changing program behavior. For example, there is a rectangle class:
Class rectangle
{
Public:
Int _ width;
Int _ height;
Virtual void setwidth (int w );
Virtual void setlenght (int l );
};
Void rectangle: setwidth (int w)
{
_ Width = W;
}
Void rectangle: setlenght (int l)
{
_ Height = L;
}
There is another square class. Because the square is a special rectangle logically, the forward release class can inherit from the rectangle class:
Class square: rectangle
{
};
At this time, the first problem will occur. Because the square's _ width and _ height are always kept, there is no need to have setwidth and setlenght functions, and this will produce errors, resulting in _ width <> _ height. to avoid this problem, rewrite the subclass square to overwrite the two functions of the parent class.
Class square: rectangle
{
Void setwidth (int w );
Void setlenght (int l );
}
Void square: setwidth (int w)
{
_ Width = _ Height = W;
}
Void square: setlength (int l)
{
_ Width = _ Height = L;
}
This avoids the above problems. At this time, there is an old object-oriented problem. Because the parent class does not declare its function as a virtual function, it is impossible to achieve dynamic help, so we can rewrite the function of the parent class to a virtual function:
Class rectangle
{
Public:
Int _ width;
Int _ height;
Virtual void setwidth (int w );
Virtual void setlenght (int l );
};
This structure seems to be okay, but in the following case, if there is a function, its input parameter is a reference of the rectangle class:
Void fun (rectangle & RT)
{
Rt. setwidth (5 );
Rt. setheight (4 );
Assert (_ width * _ Height = 20 );
}
In this way, when a square object is passed in, this asserted will be triggered, and some exceptions and unpredictable events will occur. Therefore, we should try to avoid such situations during the design so that our classes can have better adaptability, especially when the class structure we designed will be used by others.