派生对象和基类对象指针的使用(类型兼容性规则).cpp 750 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include <iostream>
  2. using namespace std;
  3. class BaseClass {
  4. public:
  5. void fn1() {
  6. cout << "the fn1 founction of the baseclass" << endl;
  7. }
  8. void fn2() {
  9. cout << "the fn2 founction of the baseclass" << endl;
  10. }
  11. };
  12. class DerivedClass : public BaseClass {
  13. public:
  14. void fn1() {
  15. cout << "the fn1 founction of the DerivedClass" << endl;
  16. }
  17. void fn2() {
  18. cout << "the fn2 founction of the DerivedClass" << endl;
  19. }
  20. };
  21. int main() {
  22. DerivedClass derivedObj;
  23. derivedObj.fn1();
  24. derivedObj.fn2();
  25. BaseClass* basePtr = &derivedObj;
  26. basePtr->fn1();
  27. basePtr->fn2();
  28. DerivedClass* derivedPtr = &derivedObj;
  29. derivedPtr->fn1();
  30. derivedPtr->fn2();
  31. return 0;
  32. }