2022.4.23编程一小时打卡

发布时间 2023-04-23 21:48:08作者: 信2211-8李欣垚

一、问题描述:

定义一个基类,派生出子类,基类有fn1(),fn2(),fn1()是虚函数;子类也有这俩个函数,在主函数中声明子类的一个对象,并通过指针调用这俩个函数。观察程序运行过程。

二、解题思路:

首先,定义一个基类BaseClass类,其派生出子类DerivedClass类,在主函数中定义基类的指针,调用这俩个函数进行代码的运行调试,验证代码的运行过程。

三、代码实现:

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class BaseClass
 5 {
 6 public:
 7     virtual void fn1();
 8     void fn2();
 9 };
10 void BaseClass::fn1()
11 {
12     cout<<"BaseClass fn1()"<<endl;
13 }
14 void BaseClass::fn2()
15 {
16     cout<<"BaseClass fn2()"<<endl;
17 }
18 class DerivedClass:public BaseClass
19 {
20 public:
21     void fn1();
22     void fn2();
23 };
24 void DerivedClass::fn1()
25 {
26     cout<<"DerivedClass fn1()"<<endl;
27 }
28 void DerivedClass::fn2()
29 {
30     cout<<"DerivedClass fn2()"<<endl;
31 }
32 int main()
33 {
34     BaseClass *b;
35     DerivedClass *d;
36     DerivedClass c;
37     b=&c;
38     b->fn1();
39     b->fn2();
40     d=&c;
41     d->fn1();
42     d->fn2();
43     return 0;
44 }

一、问题描述:

对类Point重载“++”、“--”运算符,要求同时重载前缀和后缀的形式。

二、解题思路:

首先,定义一个Point类,在类内重载自增++和自增--的运算符重载,最后,进行代码调试运行,验证程序的实行。

三、代码实现:

 

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class Point
 5 {
 6 private:
 7     int point;
 8 public:
 9     Point():point(0){}
10     Point& operator++();
11     Point operator++(int);
12     Point& operator--();
13     Point operator--(int);
14     void display();
15 };
16 Point& Point::operator++()
17 {
18     point++;
19     return *this;
20 }
21 Point Point::operator++(int)
22 {
23     ++point;
24     return *this;
25 }
26 Point& Point::operator--()
27 {
28     point--;
29     return *this;
30 }
31 Point Point::operator--(int)
32 {
33     --point;
34     return *this;
35 }
36 void Point::display()
37 {
38     cout<<point<<endl;
39 }
40 int main()
41 {
42     Point p;
43     p.display();
44     (p++).display();
45     (++p).display();
46     (p--).display();
47     (--p).display();
48     return 0;
49 }

一、问题描述:

编写程序定义类point有数据成员x,y,为其定义友元函数实现重载“+”。

二、解题思路:

首先定义一个类,然后定义一个重载运算符,最后进行代码的运行调试。
三、代码实现:

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class BaseClass
 5 {
 6 public:
 7     virtual ~BaseClass()
 8     {
 9         cout<<"BaseClass Destruct"<<endl;
10     }
11 };
12 class DerivedClass:public BaseClass
13 {
14 public:
15     ~DerivedClass()
16     {
17         cout<<"DerivedClass Destruct"<<endl;
18     }
19 };
20 int main()
21 {
22     BaseClass *p=new DerivedClass;
23     delete p;
24     return 0;
25 }