作业1-1

  • 题目:

    题目:编写C++程序,实现对3个变量(键盘输入)按由小到大顺序排序后输出,要求使用变量的引用。

  • 前置知识

    • 引用 &
      • 即将某个变量作为另外一个变量的别名, 就比如 一个人有真实名字和笔名一样
      • 例如:
        • image.png
        • 那么 a等于10, b 也等于10
        • 但是如果我这样image.png
        • 那么 a 等于多少呢? b 等于多少呢?
        • 答案是: a = 20 , b = 20; 这就是引用,因为 b 是 a 的别名, b 变了, a 也就变了
      • 函数中的引用同理:
        • 例如下面的函数swap(int &a,int &b) 也是如此
        • 那我们在这里做个比较
        • image.png
        • 这段里面注意⚠️swap1函数中有引用, swap2中无引用, 那么a ,b ,c ,d = ?
        • 答案是 a = 20, b = 10, c = 30 , d = 40 你做对了吗?
  • 代码(方式1):

    1. #include<iostream>
    2. using namespace std;
    3. // 交换两个变量的内容
    4. void swap(int &a,int &b){
    5. int temp = a;
    6. a = b;
    7. b = temp;
    8. }
    9. int main(){
    10. int a,b,c;
    11. cout<<"请输入3个变量:";
    12. cin>>a;
    13. cout<<"请输入第2个变量:";
    14. cin>>b;
    15. cout<<"请输入第3个变量:";
    16. cin>>c;
    17. cout<<"排序后:";
    18. if (a > b)
    19. {
    20. swap(a,b);
    21. }
    22. if (b > c)
    23. {
    24. swap(b,c);
    25. }
    26. if(a > b){
    27. swap(a,b);
    28. }
    29. cout<<a<<" "<<b<<" "<<c<<endl;
    30. return 0;
    31. }
  • 运行结果

    • image.png
  • 代码( 方式2, 可以不看 ):

    1. #include<iostream>
    2. #include<algorithm> // 算法头文件
    3. using namespace std;
    4. int main(){
    5. int a,b,c,i;
    6. int n[3];
    7. cout<<"请输入第1个变量:";
    8. cin>>a;
    9. n[0] = a;
    10. cout<<"请输入第2个变量:";
    11. cin>>b;
    12. n[1] = b;
    13. cout<<"请输入第3个变量:";
    14. cin>>c;
    15. n[2] = c;
    16. cout<<"排序后:";
    17. sort(n,n+3); // algorithm中内置的排序头文件(默认升序排列),第一个参数是指针(数组)名,第二个参数是指针(数组)名+需要排序的个数
    18. // 下面的for将数组n的内容循环输出
    19. for(i=0;i<3;i++){
    20. cout<<n[i]<<",";
    21. }
    22. return 0;
    23. }
  • 运行结果:

image.png

作业1-2

  • 题目:

    编写c++程序,重载sort函数。使得可以对一维整型数组、字符数组进行从小到大排序。主函数调用sort时从键盘输入数组的维数,然后用new运算符动态生成数组,数组内初始数据可以用随机分配。

  • 前置知识点

    • 重载函数:
      • 即: 两个或两个以上的函数, 函数名相同, 返回参数相同, 参数不同的函数 ( 同名不同参 )
        • image.png
      • 如下面的代码:
        • 两个sort函数函数名相同, 参数列表中第一个参数 a 的类型类型不同, 所以这两个sort() 就是重载函数
  • 代码: ```cpp

    include

    include

    include

    using namespace std;

void sort(int a,int n); void sort(char a,int n); int main(){ int q,N; char c; cout<<”请输入数组长度:”; cin>>N; q = new int[N]; c = new char[N]; srand(int(time(0))); // 为rand()加入当前时间, 每次启动随机数的值都会改变 for(int i = 0; i < N ; i++){ q[i] = rand()%100+1; // 随机数 [1,100) 左开右闭 c[i] = ((rand()%26) + ‘a’); // 随机字符 [‘a’,’z’] } sort(q,N); sort(c,N); // 将数组 q 内容输出 for(int i = 0;i < N ;i++){ cout< a[j+1]){ int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } } void sort(char a[],int n){ for(int i = 0;i < n ; i++){ for(int j = 0 ; j < n - i - 1; j++){ if(a[j] > a[j+1]){ char temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } }

  1. - 运行结果
  2. ![image.png](https://cdn.nlark.com/yuque/0/2022/png/26390413/1654591105814-56ac6570-3596-4466-a213-932e62cd16f9.png#clientId=uddc281e2-d8f3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=87&id=uba4d0342&margin=%5Bobject%20Object%5D&name=image.png&originHeight=116&originWidth=708&originalType=binary&ratio=1&rotation=0&showTitle=false&size=17421&status=done&style=none&taskId=uaae3a7b9-aba1-4159-901c-294340eaa2c&title=&width=531)
  3. ```cpp
  4. #include<iostream>
  5. using namespace std;
  6. void sort(int a[],int n){
  7. for(int i = 0;i < n ; i++){
  8. for(int j = 0 ; j < n; j++){
  9. if(a[j] > a[j+1]){
  10. int temp = a[j];
  11. a[j] = a[j+1];
  12. a[j+1] = temp;
  13. }
  14. }
  15. }
  16. }
  17. void sort(char a[],int n){
  18. for(int i = 0;i < n ; i++){
  19. for(int j = 0 ; j < n - i - 1; j++){
  20. if(a[j] > a[j+1]){
  21. char temp = a[j];
  22. a[j] = a[j+1];
  23. a[j+1] = temp;
  24. }
  25. }
  26. }
  27. }
  28. int main(){
  29. // 初始化数组
  30. int q[] = {88,76,39,99,200,19};
  31. char c[] = {'a','f','o','w','s','b'};
  32. // 将数组排序
  33. sort(q,6);
  34. sort(c,6);
  35. // 将数组 q 内容输出
  36. for(int i = 0;i < 6 ;i++){
  37. cout<<q[i]<<" ";
  38. }
  39. cout<<endl; // 换行
  40. // 将数组 c 内容输出
  41. for(int i = 0;i < 6 ;i++){
  42. cout<<c[i]<<" ";
  43. }
  44. return 0;
  45. }
  • 扩展:

    • 本题中所要求的重载函数, 仅有字符类型不同, 所以抛开题目另言, 我们可以通过模板函数的方式完成该题目, 将两个sort函数更改为一个模版函数可以改为
      template<typename T>
      void swap(T a[], int index1, int index2){
      T temp = a[index1];
      a[index1] = a[index2];
      a[index2] = temp;
      }
      template <typename T>
      void sort(T a[],int n){
      // 冒泡排序法,另其降序排列
      for (int i = 0; i < n; i++)
      {
         for (int j = 0; j < n - 1; j++)
         {
             if (a[j] > a[j+1]){
                 swap(a,j,j+1);
             }
         }
      }
      }
      

      作业2-1(类与对象一)

  • 题目:

    建立圆柱体类cylinder, 其构造函数被传递了两个double 值,分别表示圆柱体的半径和高度。定义cylinder的成员函数cal( )计算圆柱体的体积,并存储在一个double 变量中。定义类cylinder的成员函数disp( ),用来显示每个cylinder对象的体积。

  • 前置知识:

    • 类与对象
    • const 修饰符, 放在变量名类型之前
      • 作用: 一旦定义, 就不可以改变这个变量的值,否则报错,无法运行
  • 解题步骤
  • 代码:

    #include<iostream>
    using namespace std;
    // 定义在最外面的变量名为 全局变量名(全局即: 在该文件内任何地方都可以使用)
    const double PI = 3.14; 
    // 圆柱体类cylinder
    class cylinder{
      public: // 公有成员函数
          cylinder(double r,double h); // 构造函数,创建对象时触发,无返回值
          void cal(); // 计算体积函数
          void disp(); // 显示圆柱体相关信息
      private: // 私有成员属性
          double r; // 半径
          double h; // 高度
          double v; // 体积
    };
    cylinder::cylinder(double r,double h){
      this->r = r;
      this->h = h;
    }
    void cylinder::cal(){
      this->v = PI * r * r * h; // 将计算的体积
    }
    void cylinder::disp(){
      cout<<"圆柱体的体积是:"<<v;
    }
    int main(){
      double r,h;
      // 输入圆柱体信息
      cout<<"请输入圆柱体的半径:";
      cin>>r;
      cout<<"请输入圆柱体的高:";
      cin>>h;
      // 创建一个对象
      cylinder c1(r,h);
      // 通过 对象名.函数名() 调用函数
      c1.cal();
      c1.disp();
    }
    
  • 运行结果

image.png

作业2-2

  • 题目

    构建一个类Stock,含字符数组stockcode[]及整型数据成员quan、双精度型数据成员price。构造函数含3个参数:字符数组na[]、q和p。当定义Stock的类对象时,将对象的第1个字符串参数赋给数据成员stockcode, 第2和第3个参数分别赋给quan和price。未设置第2和第3个参数时,quan 的值为1000、 price的值为8.98。成员函数print()没有形参,需使用this指针,显示对象数据成员的内容。假设类Stock第1个对象的3个参数分别为:”600001”. 3000和5.67;第2个对象的第1个数据成员的值是”600001”,第2和第3个数据成员的值取默认值。编写程序分别显示这两个对象数据成员的值。

  • 代码:

    #include<iostream>
    using namespace std;
    class Stock{
      public:
          Stock(char *na); // 构造函数
          Stock(char *na,int q,double p); // 构造函数
          ~Stock(); // 析构函数
          void print(); // 输出信息
      private:
          char *stockcode; //字符数组 / 字符指针
          int quan;
          double price;
    };
    Stock::Stock(char *na){
      // 将 quan 和 price 以默认值形式传入
      stockcode = na;
      quan = 1000;
      price = 8.98;
    }
    Stock::Stock(char *na,int q,double p){
      stockcode = na;
      quan = q;
      price = p;
    }
    Stock::~Stock(){
      stockcode[0] = '\0';
      delete []stockcode; // 清除私有成员属性中的指针内容
    }
    void Stock::print(){
      cout << "Stock{stockcode:" << this->stockcode << ",quan:" << this->quan << ",price:" << this->price << "}" <<endl;
    }
    int main(){
      char* ch = "60098";
      Stock s1(ch,3000,5.67);
      Stock s2(ch);
      s1.print();
      s2.print();
    }
    
  • 运行结果:

image.png

作业3-1(类与对象二)

  • 题目

    建立一个对象数组,内放5个学生的数据(学号、成绩),设立一个函数max,用对象引用作函数参数,在max函数中找出5个学生中成绩最高者,并输出其学号。

  • 前置知识:

  • 代码:

    #include <iostream>
    using namespace std;
    class Student {
      public:
          Student(long sid = 0L,int sc = 0):stuid(sid),score(sc){}
          void input(); // 输入函数(接收用户输入的学号和分数)
          void show(); // 展示值函数
          long getStuid(); // 获取学号
          int getScore(); // 获取分数
          static Student max(Student stu[],int n); // 获取最大值(从大到小排序数组);stu为数组, n为数组个数
      private:
          long stuid;
          int score;
    };
    void Student::input(){
      cin>>stuid>>score;
    }
    void Student::show(){
      cout<<"Student{stuid="<<this->stuid<<",score="<<this->score<<"}"<<endl;
    }
    long Student::getStuid(){
      return this->stuid;
    }
    int Student::getScore(){
      return this->score;
    }
    Student Student::max(Student stu[],int n){
      Student max = stu[0];
      for (int i = 0; i < n; i++)
      {
          if(max.getScore() < stu[i].getScore()){
              max = stu[i];
          }
      }
      return max;
    }
    int main(){
      Student stu[5];
      for(int i = 0; i < 5; i++){
          cout<<"请输入第"<<i+1<<"位同学的信息"<<endl;
          stu[i].input();
      }
      Student maxStu = Student::max(stu,5);
      // 取第一个即为最大值
      cout<<"成绩最高的同学的学号是:"<<maxStu.getStuid()<<endl;
    }
    
    #include <iostream>
    using namespace std;
    class Student {
      public:
          Student(long sid = 0L,int sc = 0):stuid(sid),score(sc){}
          void input(); // 输入函数(接收用户输入的学号和分数)
          void show(); // 展示值函数
          long getStuid(); // 获取学号
          int getScore(); // 获取分数
          static void max(Student stu[],int n); // 获取最大值(从大到小排序数组);stu为数组, n为数组个数
      private:
          long stuid;
          int score;
    };
    void Student::input(){
      cin>>stuid>>score;
    }
    void Student::show(){
      cout<<"Student{stuid="<<this->stuid<<",score="<<this->score<<"}"<<endl;
    }
    long Student::getStuid(){
      return this->stuid;
    }
    int Student::getScore(){
      return this->score;
    }
    void Student::max(Student stu[],int n){
      for (int i = 0; i < n; i++)
      {
          for (int j = 0; j < n - 1; j++)
          {
              if(stu[j].getScore() < stu[j+1].getScore()){
                  Student temp = stu[j];
                  stu[j] = stu[j+1];
                  stu[j+1] = temp;
              }
          }
      }
    }
    int main(){
      Student stu[5];
      for(int i = 0; i < 5; i++){
          cout<<"请输入第"<<i+1<<"位同学的信息"<<endl;
          stu[i].input();
      }
      Student::max(stu,5);
      // 取第一个即为最大值
      cout<<"成绩最高的同学的学号是:"<<stu[0].getStuid()<<endl;
    }
    
  • 运行结果

image.png

作业3-2

  • 题目

    商店销售某一商品,商店每天公布统一的折扣(discount)。同时允许销售人员在销售时灵活掌握售价(price),在此基础上,对一次购10件以上者,还可以享受9.8折优惠。现已知当天3个销货员的销售数量情况为:
    销货员号(num) 销货件数(quantity) 销货单价(price) 101 5 23.5 102 12 24.56 103 100 21.5 请编程序,计算出当天此商品的总销售款sum以及每件商品的平均售价。要求用静态数据成员和静态成员函数。

  • 前置知识:

    • 三目运算符( 表达式 ? a : b)
      • 三目运算符的扩展即为if()语句
      • 例如:
      • image.png
      • 其中的 a > b 即为 表达式
      • 用 if 语句表示即为:
      • image.png
  • 代码 ```cpp

    include

    using namespace std; class Goods{ public:
      Goods(int num,int quantity,double price);
      void discountAll(); // 计算总销售款(已经计算的总销售款 + 这个销售员销售的件数 * 单价 * 今日折扣价 * 满减折扣价)
      static double getAverage(); // 获取平均售价(即: sum / n)
      static double getSum(); // 获取总销售款
      static double discount; // 折扣价
      static double sum;      // 总销售款(总销售金额)
      static int n;           // 总销售件数
    
    private:
      int num;      // 销货员号
      int quantity; // 销货件数
      double price; // 销货单价
    
    }; double Goods::discount = 1; // 程序运行前将静态变量赋值 double Goods::sum = 0; // 程序运行前将静态变量赋值 int Goods::n = 0; // 程序运行前将静态变量赋值 Goods::Goods(int num,int quantity,double price){ this->num = num; this->quantity = quantity; this->price = price; n += quantity; discountAll(); } void Goods::discountAll(){ sum += this->quantity this->price (discount / 10.0) * (this->quantity > 10 ? 0.98 : 1); } double Goods::getAverage(){ return sum / n; } double Goods::getSum(){ return sum; }

int main(){ cout<<”请输入今日的折扣(0~10):”<>(Goods::discount); Goods goods[3] = {Goods(101,5,23.5),Goods(102,12,24.56),Goods(103,100,21.5)}; cout<<”今天的总销售款是”<<Goods::getSum()<<endl; cout<<”每件商品平均售价”<<Goods::getAverage()<<endl; }


- 运行结果

![image.png](https://cdn.nlark.com/yuque/0/2022/png/26390413/1654595035512-391dfee4-e125-45c6-b195-bcc9547c7773.png#clientId=uc040f3c0-c6b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=115&id=ua3347ee3&margin=%5Bobject%20Object%5D&name=image.png&originHeight=142&originWidth=678&originalType=binary&ratio=1&rotation=0&showTitle=false&size=24134&status=done&style=none&taskId=ud7360f1d-fb92-4430-b1a2-6ceac4864d0&title=&width=551)
<a name="x6JEl"></a>
# 作业4-1(类与对象三)

- 题目: (同实验一)
> 设计一个表示直角坐标系的Location类,在主程序中创建类Location的两个对象A和B,分别采用成员函数和友元函数计算给定两个坐标点之间的距离,要求按如下格式输出结果:
> A(x1,y1), B(x2,y2)
> Distance=d
> 其中:x1、y1、x2、y2为指定坐标值,d为两个坐标点之间的距离。

- 前置知识
   - 友元函数 (关键字 friend )
      - 标识 `friend 返回值修饰符 函数名( 参数 ){...}`
      - 声明在类中( 可放在任何部分 ( public, private或protected ))
      - 定义可放在 类内部 或 类外部 , 且在外部定义时不需要加 friend
      - 因为友元函数不是类的成员函数
         - 所以在类外部定义时不需要添加 `类名::`以标识该函数
         - 不能通过this指向数据成员 ( 例如: `this->xxx`)
         - 只能操作参数中传进来的对象 所以友元函数必须携带对象
            -  ( 例如: `friend void calDistanceByFriend(Utils &u,Location &a,Location &b);`)
         - 当一个函数需要访问多个类时, 只需将友元函数分别声明在需要访问的类中, 外部定义一次即可 ( 详细查看下面代码 )
   - 友元类(用的不多)
   - 友元函数和友元类均可以访问对象的 public , protected , private成员
   - 友元关系不可以在类与类之间被继承
   - <br />
- 代码
```cpp
#include<iostream>
#include<math.h> // 数学库头文件
using namespace std;
class Utils;
class Location{
    public:
        double calDistance(Location &);
        Location(int x1,int y1):x(x1),y(y1){};
        friend double calDistanceByFriend(Location &a,Location &b); // 友元函数声明必须在类内部
    private:
        int x;
        int y;
};
// 通过对象调用成员函数计算两点距离
// PS: 调用方与传进来的对象距离
double Location::calDistance(Location &a){
    return sqrt(pow(this->x - a.x, 2) + pow(this->y - a.y, 2));
}
// 通过友元函数计算传进来的两个对象的距离
// PS: 友元函数定义可以在类外部, 也可以在类内部
double calDistanceByFriend(Location &a,Location &b){
    return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2));
}
int main(){
    int x1,y1,x2,y2;
    cout<<"请输入两点的坐标(x1,y1),(x2,y2)"<<endl;
    cin>>x1>>y1>>x2>>y2;
    Location a(x1,y1),b(x2,y2);
    cout<<"A("<<x1<<','<<y1<<"),B("<<x2<<','<<y2<<")"<<endl;
    // 成员函数计算
    double d = b.calDistance(a);
    cout<<"Distance="<<d<<endl;
    // 友元函数计算
    double fd = calDistanceByFriend(a,b);
    cout<<"FriendDistance="<<fd<<endl;
}
  • 运行结果:

image.png

作业5-1(继承与派生)

  • 题目:

    定义一个 Point 类,并派生出Rectangle 类和 Circle 类,计算各派生类对象的面积Area()。

  • 代码:

    #include<iostream>
    using namespace std; 
    const double PI = 3.1415; // 定义全局变量(const修饰, 变量名一般全部大写)
    // 基类Point
    class Point{
      public:
          void setArea(double area){ // set方法(访问接口), 为封装的私有area属性赋值
              this->area = area;
          }
          void show(); // 展示信息
      private:
          double area;
    };
    void Point::show(){
      cout<<"面积为:"<<area<<endl;
    }
    // Rectangle类
    class Rectangle : public Point{
      public:
          Rectangle(int slength,int swidth):length(slength),width(swidth){
              double area = length * width;
              setArea(area);
          };
      private:
          int length;
          int width;
    };
    // Circle类
    class Circle : public Point{
      public:
          Circle(int sr):r(sr){
              double area = PI * r * r;
              setArea(area);
          };
      private:
          int r;
    };
    int main(){
      int w,h,r;
      cout<<"长方形的长宽为"<<endl;
      cin>>w>>h;
      Rectangle rectangle(w,h);
      cout<<"圆形的半径为"<<endl;
      cin>>r;
      Circle circle(r);
      // 输出信息
      cout<<"Rectangle("<<w<<","<<h<<")=>";
      rectangle.show();
      cout<<"Circle("<<r<<")=>";
      circle.show();
    }
    
  • 运行结果:

image.png

作业5-2

  • 题目:

    下面的程序可以输出ASCII字符与所对应的数字的对照表。修改下面的程序,使其可以输出字母a~z与所对应的数字的对照表。 image.png image.png

  • 前置知识

    • setw( n ) 函数是#include<iomanip>头文件中库中的函数
      • n 表示宽度
      • 作用: 设置字段的宽度
      • 只对后面紧跟的输出产生作用, 当后面紧跟的字段长度小于 n 时, 在该字段前用空格补齐, 大于 n 时, 正常全部输出
  • 原代码运行结果
    • image.png
  • 修改如下:

    1. (14行) void table::ascii (void){...}函数内for循环中 i<127 改为 i < 123
    2. (36行) main 函数内 ob1 对象的构造函数赋值由 32 改为97 即可
    • 修改后代码运行结果
    • image.png

      作业6-1(虚函数)

  • 题目

    定义高度基类High,其数据成员为高h,定义成员函数disp()为虚函数。然后再由High派生出长方体类Cuboid与圆柱体类cylinder。并在两个派生类中定义成员函数disp()为虚函数。在主函数中,用基类High定义指针变量P,然后用指针P动态调用基类与派生类中虚函数disp(),显示长方体与圆柱体的体积。

  • 前置知识:

    • 虚函数
    • 动态指针
  • 代码 ```cpp

    include

    using namespace std;

const double PI = 3.1415; class High{ public: void setH(int h){ this->h = h; } int getH(){ return this->h; } virtual void disp(){ cout << “基类High中的disp()” << endl; } private: int h; }; class Cuboid : public High { public: Cuboid(int sw, int sl, int sh) : w(sw), l(sl){ this->setH(sh); } void disp(){ cout << “长方体的体积:” << w l this->getH() << endl; } private: int w; int l; }; class cylinder : public High { public: cylinder(int sr, int sh) : r(sr){ this->setH(sh); } void disp(){ cout << “圆柱体体积:” << PI r r this->getH() << endl; } private: int r; }; int main() { int w, l, h, r; cout << “请输入长方体的长、宽、高” << endl; cin >> l >> w >> h; cout << “请输入圆柱体的底面半径和高” << endl; cin >> r >> h; // High high, p; Cuboid cu(w, l, h); cylinder cy(r, h); p = &high; p->disp(); p = &cu; p->disp(); p = &cy; p->disp(); }


- 运行结果
- ![image.png](https://cdn.nlark.com/yuque/0/2022/png/26390413/1654665463267-a9aa4303-af20-4d7c-8ab5-0db021049e61.png#clientId=u6029653c-4508-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=104&id=u2ca844f9&margin=%5Bobject%20Object%5D&name=image.png&originHeight=208&originWidth=496&originalType=binary&ratio=1&rotation=0&showTitle=false&size=29270&status=done&style=none&taskId=u3655fc21-ad06-4ee9-b8f0-ee1c4b7865b&title=&width=248)
<a name="Bgw65"></a>
# 作业7-1(模板)

- 题目
> 编写一个对具有n个元素的数组x[]求最大值的程序,要求将求最大值的函数设计成函数模板。并分别使用元素类型int和double型的测试数据对其进行测试。

- 代码
```cpp
#include<iostream>
using namespace std;
// 将数组内的两个值互换位置模版
template<typename T>
void swap(T a[], int index1, int index2){
    T temp = a[index1];
    a[index1] = a[index2];
    a[index2] = temp;
}
// 获取最大值模版
template <typename T>
T max(T a[],int n){
    // 冒泡排序法,另其降序排列
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n - 1; j++)
        {
            if (a[j] < a[j+1]){
                swap(a,j,j+1);
            }
        }
    }
    return a[0];
}
int main(){
    int arr[] = {9,8,9,10,3};
    int maxInt = max(arr,5);
    cout<<"int类型数组中最大值是: "<<maxInt<<endl;
    double arrDouble[] = {9.0, 9.9, 10.3, 5.2, 4.1};
    double maxDouble = max(arrDouble,5);
    cout<<"double类型数组中最大值是:: "<<maxDouble<<endl;
}
  • 运行结果
  • image.png

    作业7-2

  • 题目

    编写一个Sample类模板,其中私有有数据成员为T da,在该类模板中设计一个“operator==”重载运算符函数,用于比较各Sample类对象的da数据是否相等。

  • 代码

    #include<iostream>
    using namespace std;
    template <class T>
    class Sample{
      public:
          Sample(T a):da(a){}
          T getDa(){
              return this->da;
          }
          bool operator== (Sample <T> &a){
              return this->da == a.getDa();
          }
      private:
          T da;
    };
    int main(){
      Sample <int> a(10),b(10);
      cout<< (a == b ? "Equal" : "Not Equal");
    }
    
  • 运行结果为 Equal

  • 若将 main 函数内的对象b( 10 ) 改为 b( 20 ), 则结果为Not Equal