栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 面向对象 - 构造函数与析构函数

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 面向对象 - 构造函数与析构函数

(1)构造函数 —— 学生信息类

#include
#include
using namespace std;
 
class Student
{

public:
Student();
Student(int sid,string name);
~Student();
int SID;
string Name;
//在此处声明所需的成员

};
 

Student::Student()
{
    SID=0;
    Name="王小明";
}
//在此处定义成员函数
Student::Student(int sid,string name)
{
    SID=sid;
    Name=name;
}
Student::~Student()
{
    cout< }

(2)对象数组 —— 学生信息表

#include
#include
using namespace std;
 

class Student
{
    //在此处声明所需的成员
    public:
    int SID;
    string Name;
    float Sco;
    Student();
    Student(int sid,string name,float sco)
    {
        SID=sid;
        Name=name;
        Sco=sco;
    }
};
    Student ss[5];
    int ssCount;
    Student::Student()
    {}   

 
 
void Add(int sid,string name,float sco)
{
   
    ss[ssCount]=Student(sid,name,sco);
    ssCount++;
   
}
 
void PrintAll()
{
   
    //打印出学生表中所有记录
    for(int i=0;i     {
        cout<     }
 
}
 
void Average()
{
   
    //计算并打印出学生表中的平均成绩
    float sum=0.00;
    float ave;
    for(int i=0;i     {
        sum+=ss[i].Sco;
    }
    ave=sum/ssCount;
    cout<<"平均成绩"<<" "<     
   
}

(3)静态成员 —— 模拟共享书店

#include
#include
using namespace std;
 

class User
{
    //在此处声明所需的成员
    public:
    static int UserCount;
    static int BookCount;
    string Name;
    int Books;
    User(string name,int books);
    ~User();
    static void GetState();   
};
int User::UserCount=0;
int User::BookCount=0;
User::User(string name,int books)
{
    UserCount++;
    Name=name;
    Books=books;
    cout<     BookCount+=Books;
}
User::~User()
{
    UserCount--;
    cout<     BookCount-=Books;
}
void User::GetState()
{
    cout<<"书店人数:"< }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/960058.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号