#include iostreamhclass A privateint a b;publicAint i int j a = i; b = j; void Moveint x int y a += x; b += y; void Show cout a b endl; ;class B private A publicBint i int j int k int
This code defines two classes, A and B.
Class A has two private data members, a and b, and a constructor that initializes them. It also has three member functions:
- Move, which takes two integers and adds them to a and b, respectively.
- Show, which prints the current values of a and b.
Class B is a derived class of A, and it has two private data members, x and y, and a constructor that initializes them as well as the base class A. It also has three member functions:
- Show, which prints the values of x and y.
- fun, which calls the Move function of the base class, adding 3 to a and 5 to b.
- f1, which calls the Show function of the base class to print the current values of a and b.
In the main function, an object e of class A is created with initial values of 1 and 2, and its Show function is called to print (1, 2).
An object d of class B is also created with initial values of 3, 4, 5, and 6. Its fun function is called, which modifies the values of a and b in the base class. Then, its Show function is called to print 5 and 6. Finally, its f1 function is called, which prints (4, 7) by calling the Show function of the base class.
Overall, this code demonstrates inheritance and access control in C++
原文地址: https://www.cveoy.top/t/topic/fff8 著作权归作者所有。请勿转载和采集!