2023.4.22编程一小时打卡

一、问题描述:

请编写一个计数器Counter类,对其重载运算符“+”。

二、解题思路: 首先编写一个Counter类,然后,进行编写运算符“+”的重载,最后,进行代码的运行编译进行验证。

三、代码实现:

复制代码
 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class Counter
 5 {
 6 private:
 7     int count;
 8 public:
 9     Counter(){}
10     Counter(int c):count(c){}
11     Counter operator+(Counter &);
12     void display();
13 };
14 Counter Counter::operator+(Counter &c)
15 {
16     Counter a;
17     a.count=count+c.count;
18     return a;
19 }
20 void Counter::display()
21 {
22     cout<<count<<endl;
23 }
24 int main()
25 {
26     Counter a(5),b(6),c;
27     c=a+b;
28     cout<<"c=a+b=";
29     c.display();
30     return 0;
31 }
复制代码

一、问题描述:

编写一个哺乳动物类Mammal,再由此派生出狗类Dog,二者都声明 speak()成员函数,该函数在基类中被声明为虚函数,声明一个Dog类的对象,通过此对象调用speak函数,观察运行结果。

二、解题思路:

 首先,编写基类Mammal类,在定义子类Dog,在基类中定义一个虚函数speak(),在子类中重新定义,最后在主函数中用子类的对象进行代码的运行调试。

三、代码实现:

复制代码
 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class Mammal
 5 {
 6 public:
 7     virtual void speak();
 8 };
 9 void Mammal::speak()
10 {
11     cout<<"Mammal"<<endl;
12 }
13 class Dog:public Mammal
14 {
15 public:
16     void speak();
17 };
18 void Dog::speak()
19 {
20     cout<<"Dog"<<endl;
21 }
22 int main()
23 {
24     Dog d;
25     d.speak();
26     return 0;
27 }
复制代码

一、问题描述:

请编写一个抽象类Shape,在此基础上派生出类Rectangle和Circle,二者都有计算对象面积的函数getArea()、计算对象周长的函数getPerim()。

二、解题思路:

 首先,定义基类Shape为抽象类,在定义其俩个子类Rectangle和Circle,最后,用基类的指针去调用俩个子类的函数进行代码的运行调试。

三、代码实现:

 

复制代码
 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class Shape
 5 {
 6 private:
 7     double width,height;
 8 public:
 9     virtual void getArea()=0;
10     virtual void getPerim()=0;
11 };
12 class Rectangle:public Shape
13 {
14 private:
15     double width,height;
16 public:
17     Rectangle(double a,double b):width(a),height(b){}
18     void getArea();
19     void getPerim();
20 };
21 void Rectangle::getArea()
22 {
23     cout<<width*height<<endl;
24 }
25 void Rectangle::getPerim()
26 {
27     cout<<2*(width+height)<<endl;
28 }
29 class Circle:public Shape
30 {
31 private:
32     double r;
33 public:
34     Circle(double a):r(a){}
35     void getArea();
36     void getPerim();
37 };
38 void Circle::getArea()
39 {
40     cout<<3.1415*r*r<<endl;
41 }
42 void Circle::getPerim()
43 {
44     cout<<3.1415*2*r<<endl;
45 }
46 int main()
47 {
48     Shape *p;
49     Rectangle c(3,4);
50     Circle r(3);
51     p=&c;
52     p->getArea();
53     p->getPerim();
54     p=&r;
55     p->getArea();
56     p->getPerim();
57     return 0;
58 }
复制代码
posted @   信2211-8李欣垚  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示