编程语言
首页 > 编程语言> > 学习笔记-C++

学习笔记-C++

作者:互联网

题目:声明一个基类BaseClass,从它派生出类DerivedClass,BaseClass有成员函数fn1()和fn2(),fn1()是虚函数,DerivedClass也有成员函数fn1()和fn2(),在主函数中声明一个DerivedClass的对象,分别用BaseClass和DerivedClass的指针指向DerivedClass的对象,并通过指针调用fn1()和fn2()。并画出类图。

 1 #include<iostream>
 2 using namespace std;
 3 //声明一个基类BaseClass
 4 //虚函数为fn1()
 5 class BaseClass
 6 {
 7 public:
 8     virtual void fn1();
 9     void fn2();
10 protected:
11 
12 };
13 void BaseClass::fn1()
14 {
15     cout << "调用基类的虚函数" << endl;
16 }
17 void BaseClass::fn2()
18 {
19     cout << "调用基类的非虚函数" << endl;
20 }
21 //派生出类DerivedClass
22 class DerivedClass:public BaseClass
23 {
24 public:
25     void fn1();
26     void fn2();
27 private:
28 
29 };
30 void DerivedClass::fn1()
31 {
32     cout << "调用子类fn1()函数" << endl;
33 }
34 void DerivedClass::fn2()
35 {
36     cout << "调用子类的fn2()函数" << endl;
37 }
38 int main()
39 {
40     DerivedClass d;//主函数中声明的derivedclass对象
41     DerivedClass* d1 = &d;
42     BaseClass* b1 = &d;
43 
44     b1->fn1();
45     b1->fn2();
46 
47     d1->fn1();
48     d1->fn2();
49     system("pause");
50     return 0;
51 }

运行截图

 

 类图

 

标签:fn2,fn1,void,笔记,学习,C++,函数,BaseClass,DerivedClass
来源: https://www.cnblogs.com/army613bts/p/14154579.html