【Educoder作业】C++ 面向对象 - 构造函数与析构函数

【Educoder作业】C++ 面向对象 - 构造函数与析构函数

这个感觉没啥需要说的,就是一类特殊的函数。
有的时候题目报错的话,可以看看是不是没写构造函数。

T1 构造函数 —— 学生信息类

写法真的很多。我大多数情况下更喜欢在类的定义时就写好函数。

#include<iostream>
#include<string>
using namespace std;

class Student
{
    
    
/********* Begin *********/
	public :
	Student() {
    
    SID = 0; Name = "王小明";}
	Student(int sid, string name) {
    
    SID = sid, Name = name;}
	~Student() {
    
    cout << SID << ' ' << Name << " 退出程序" << endl ;}
	private :
	int SID; string Name;
//在此处声明所需的成员

/********* End *********/
};

/********* Begin *********/

//在此处定义成员函数

/********* End *********/

T2 对象数组 —— 学生信息表

这个题就是,如果不写空构造函数的话,在定义数组的时候就会报错。

#include <string>
#include <iostream>
using namespace std;

/********* Begin *********/
class Student
{
    
    
	//在此处声明所需的成员
    public :
	int SID;
	string Name;
	float Sco;
	Student() {
    
    }
	Student(int sid, string name, float sco) {
    
    SID = sid, Name = name, Sco = sco;}
    
    
};
Student st[10010];
int cnt;
/********* End *********/


void Add(int sid,string name,float sco)
{
    
    
    /********* Begin *********/
	st[ ++ cnt] = Student(sid, name, sco);
    /********* End *********/
}

void PrintAll()
{
    
    
    /********* Begin *********/
    //打印出学生表中所有记录
	for (int i = 1; i <= cnt; i ++ )
		cout << st[i].SID << ' ' << st[i].Name << ' ' << st[i].Sco << endl ;
    /********* End *********/
}

void Average()
{
    
    
    /********* Begin *********/
    //计算并打印出学生表中的平均成绩
	float sum = 0;
	for (int i = 1; i <= cnt; i ++ ) sum += st[i].Sco;
	cout << "平均成绩 " << sum / cnt << endl ;
    
    
    /********* End *********/
}

T3 静态成员 —— 模拟共享书店

静态成员就是一整个类共享的变量,有点像类层面的全局变量。

#include <string>
#include <iostream>
using namespace std;

/********* Begin *********/
class User
{
    
    
	//在此处声明所需的成员
	public :
	// User() {}
	User(string name, int books);
	~User();
	static void GetState();
    private :
	string Name;
	int Books;
	static int UserCount, BookCount;
    
    
};
//在此处定义成员函数

int User :: UserCount = 0, User :: BookCount = 0;

User :: User(string name, int books) {
    
    
	Name = name, Books = books;
	cout << Name << ' ' << Books << " 进入" << endl ;
	UserCount ++ , BookCount += Books;
}

User :: ~User() {
    
    
	cout << Name << ' ' << Books << " 离开" << endl ;
	UserCount -- , BookCount -= Books;
}

void User :: GetState() {
    
    
	cout << "书店人数:" << UserCount << ",书店共享书数量:" << BookCount << ",人均共享数量:" << BookCount / UserCount <<endl ;
}
/********* End *********/

猜你喜欢

转载自blog.csdn.net/JZYshuraK/article/details/128521869