C++ 程序示例:函数调用、类继承与多态
#include <iostream.h> void sub(int x, int y, int *z) { *z = y + x; } void main() { int a, b, c; sub(8, 4, &a); sub(6, a, &b); sub(a, b, &c); cout << a << "," << b << "," << c << endl; }
运行结果: 12,18,30
#include <iostream.h> class A { private: int a, b; public: A(int i, int j) { a = i; b = j; } void Move(int x, int y) { a += x; b += y; } void Show() { cout << "( " << a << ", " << b << " )" << endl; } }; class B : private A { public: B(int i, int j, int k, int l) : A(i, j) { x = k; y = l; } void Show() { cout << x << " ," << y << endl; } void fun() { Move(3,5); } void f1() { A :: Show(); } private: int x, y; }; void main() { A e(1, 2); B d(3, 4, 5, 6); e.Show(); d.fun(); d.Show(); d.f1(); }
运行结果: ( 1, 2 ) 5 ,6 ( 4, 7 )
#include <iostream.h> class A { public: virtual void fun() { cout << "A::fun" << endl; } }; class B : public A { public: void fun() { cout << "B::fun" << endl; } }; void main() { A a; B b; A *p = &a; p->fun(); p = &b; p->fun(); }
运行结果: A::fun B::fun
原文地址: https://www.cveoy.top/t/topic/oaq3 著作权归作者所有。请勿转载和采集!