介绍
本文 主要介绍用类去创建一个现实中基本对象的 实例化操作
1.创建一个Dog,属性有姓名,犬龄,品种,毛色(不可以外部直接设置).行为有进食,奔跑,睡觉。
2.创建一个对象数组,存放4个学生(学号,成绩)(学号和成绩不可外部直接设置,且设置学号时不可重复),
设计一个函数max,找出这4个学生成绩最高的,并输出学号
源码
lesson_1
#include<iostream>
#include<string>using namespace std;
class Dog
{
public://设置狗狗基础信息void set_Dog(string name,int age,string variety,string colour){N_name = name;A_age = age;V_variety = variety;C_colour = colour;}void rush(){cout << N_name << "奔跑中" << endl;}void sleep(){cout << N_name << "睡觉中" << endl;}void eat(){cout << N_name << "吃饭中" << endl;}void print(){cout << N_name << " " << V_variety << " " << A_age << " " << C_colour << endl;}
private:string N_name;//名字string V_variety;//品种string C_colour;//颜色int A_age;//年龄
};
void main()
{
//栈区对象Dog wc;//构造一个对象旺财wc.set_Dog("旺财", 3, "中华田园犬", "黄色");wc.print();wc.eat();wc.rush();wc.sleep();cout << "------------------------区分线------------------------" << endl;
//堆区对象Dog *ch = new Dog;//构造一个对象旺财ch->set_Dog("翠花", 2, "哈士奇", "黑白相间");ch->print();ch->eat();ch->rush();ch->sleep();delete ch;system("pause");
}
lesson_2
#include<iostream>
#include<string>using namespace std;class Student
{
public://设置学生基础信息void set_student(string name, int score, string number){N_name = name;S_score = score;N_number = "23120" + number;}void print(){cout << N_name << " " << S_score << " " << N_number << endl;}int getscore(){return S_score;}private:string N_name;//名字int S_score;//成绩string N_number;//学号
};
void max(Student* st,int len)
{Student temp= st[0];for (int i = 0; i < len; i++){if (temp.getscore()<st[i + 1].getscore()){temp = st[i + 1];}}temp.print();
}
void main()
{string name;//名字int score;//成绩string number;//学号Student st[4];//输入学生信息for (int i = 0; i < 4; i++){cin >> name >> score >> number;st[i].set_student(name, score, number);}max(st,4);system("pause");
}