C++编程基础二 28-复习2

  1 // C++函数和类 28-复习2.cpp: 定义控制台应用程序的入口点。
  2 //
  3 
  4 #include "stdafx.h"
  5 #include<iostream>
  6 #include<string>
  7 
  8 using namespace std;
  9 
 10 //定义类,class关键字 类名
 11 //类的数据成员(私有private),类的成员方法(公有public).
 12 //私有成员:只能在类的内部进行访问。公有成员:既可以在类的内部进行访问,也可以在类的外部通过对象进行访问。
 13 
 14 class Student
 15 {
 16     //作用域为类的常量,需要加上static关键字,因为需要给常量分配内存空间。
 17     static const int PassingScore = 500;
 18     //友元函数,写在类的外部,但是可以通过类的对象去访问类的私有成员。它不是类的成员方法。
 19     //使用friend 关键字
 20     friend void pass(Student &s);
 21 private:
 22     string name_;
 23     int age_;
 24     int score_;
 25 public:
 26     //构造函数和析构函数
 27     Student();
 28     Student(string name, int age, int score);
 29     ~Student();
 30     
 31     //成员方法:
 32     void print();
 33     bool max(Student &s);
 34 };
 35 
 36 //类方法的定义
 37 Student::Student()
 38 {
 39     name_ = "";
 40     age_ = 0;
 41     score_ = 0;
 42 }
 43 
 44 Student::Student(string name, int age, int score)
 45 {
 46     name_ = name;
 47     age_ = age;
 48     score_ = score;
 49 }
 50 
 51 Student::~Student()
 52 {
 53 
 54 }
 55 
 56 void Student::print()
 57 {
 58     cout << "该学生的姓名:" << name_ << ",该学生的年龄: " << age_ << ",该学生的年龄: " << "该学生的分数: " << score_ << endl;
 59 }
 60 
 61 //this指针
 62 bool Student::max(Student & s)
 63 {
 64     return this->score_ >= s.score_ ? true : false;
 65 }
 66 
 67 void sort(Student stuss[], int size)
 68 {
 69     Student temp;
 70     for (int i = 0; i < size - 1; i++)
 71     {
 72         for (int j = i + 1; j < size; j++)
 73         {
 74             if (stuss[i].max(stuss[j]) == false)
 75             {
 76                 temp = stuss[i];
 77                 stuss[i] = stuss[j];
 78                 stuss[j] = temp;
 79             }
 80         }
 81     }
 82 }
 83 
 84 void pass(Student &s)
 85 {
 86     if (s.score_ >= s.PassingScore)
 87     {
 88         cout << s.name_<< "通过了该次考试!" << endl;
 89     }
 90     else
 91     {
 92         cout << s.name_<< "没有通过该次考试!" << endl;
 93     }
 94 }
 95  int main()
 96 {
 97      Student stu1("uimodel", 10, 550);
 98      Student stu2("Lebin", 12, 520);
 99 
100      stu1.print();
101      bool res = stu2.max(stu1);
102      if (res == true)
103      {
104          cout << "uimodel的分数比Lebin高" << endl;
105      }
106      else
107      {
108          cout << "Lebin的分数比uimodel高" << endl;
109      }
110 
111      const int size = 3;
112      Student stuss[size];
113      stuss[0] = Student("Tom", 13, 480);
114      stuss[1] = Student("Bobo", 20, 460);
115      stuss[2] = Student("James", 15, 510);
116 
117      sort(stuss, size);
118      for (int i = 0; i < size; i++)
119      {
120          stuss[i].print();
121          pass(stuss[i]);
122      }
123 
124      pass(stu2);
125     return 0;
126 }

猜你喜欢

转载自www.cnblogs.com/uimodel/p/9348643.html
28-
今日推荐