tailieunhanh - C++ Weekend Crash Course phần 8

Tuy nhiên, định nghĩa này mặc định là không chính xác cho các lớp phân bổ nguồn lực, chẳng hạn như bộ nhớ heap. Các lập trình viên phải tình trạng quá tải nhà điều hành = () để xử lý việc chuyển giao các nguồn lực. | 354 Sunday Morning include include class Furniture public Furniture cout Creating the furniture concept int weight class Bed virtual public Furniture public Bed cout Building the bed part n void sleep cout Trying to get some sleep over here n class Sofa virtual public Furniture public Sofa cout Building the sofa part n void watchTV cout Watching TV n SleeperSofa - is both a Bed and a Sofa Session 24 Multiple Inheritance 355 class SleeperSofa public Bed public Sofa public the constructor doesn t need to do anything SleeperSofa cout Putting the two together n void foldOut cout Folding the bed out n int main output the weight of the sleepersofa SleeperSofa ss cout sofa weight this doesn t work weight this does work n return 0 Notice the addition of the keyword virtual in the inheritance of Furniture in Bed and Sofa. This says Give me a copy of Furniture unless you already have one somehow in which case I ll just use that one. A SleeperSofa ends up looking like Figure 24-5 in memory. Furniture SleeperSofa Bed stuff Sofa stuff SleeperSofa stuff Part V-Sunday Morning Session 24 Figure 24-5 Memory layout of SleeperSofa with virtual inheritance 356 Sunday Morning A SleeperSofa inherits Furniture then Bed minus the Furniture part followed by Sofa minus the Furniture part. Bringing up the rear are the members unique to SleeperSofa. This may not be the order of the elements in memory but that s not important for our purposes. The reference in main to weight is no longer ambiguous because a SleeperSofa contains only one copy of Furniture. By inheriting Furniture virtually you get the desired inheritance relationship as expressed in Figure 24-2. If virtual inheritance solves this problem so nicely why isn t it the norm There are two reasons. First virtually inherited base classes are handled internally much differently than normally inherited base classes and these differences involve extra overhead. Not that much extra overhead but the .

TỪ KHÓA LIÊN QUAN