在c++中构造函数和析构函数的应用中出现的一些问题

本文介绍了一个使用C++实现的学生信息类,该类能够创建包含姓名、学号及成绩的学生对象,并提供了修改成绩和展示学生信息的方法。


#include<iostream>
#include<cstring>
using namespace std;
struct Student
{
public:
    Student(char *name1,char *stu_no1,float score1);
    ~Student();
    void modify(float score);
    void show();
private:
    char *name;
    char *stu_no;
    float score;
};
Student::Student(char *name1,char *stu_no1,float score1)
{                                //因为strlen返回的是字符串所占的个数  并不包括‘/0’;
    name=new char[strlen(name1)+1];//new为具有name1+1个char型元素分配了内存空间,并将首地址赋给了指针name,后面加上的1是‘/0’所占空间,即结束符
    strcpy(name,name1);//将后者所指空间中的内容复制到前者所指的空间中
    stu_no=new char[strlen(stu_no1)+1];
    strcpy(stu_no,stu_no1);
    score=score1;
}
Student::~Student()
{
    delete []name;
    delete []stu_no;
}
void Student::show()
{
    cout<<"name:  "<<name<<endl;//cout 对于运算符<<重载,表示输出从char*所指向的首地址到结束符前面的内容
    cout<<"stu_no:  "<<stu_no<<endl;
    cout<<"score:  "<<score<<endl;
}
void Student::modify(float score1)
{
    score=score1;
}
int main()
{
    Student stu1("liming","20080201",90);
    stu1.show();
    stu1.modify(80);
    stu1.show();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿的探索之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值