C++面向对象 class two

  • c++的动态申请内存:this->name = new char[strlen(name)+1]; //[]里面的是元素数而不是字节数。
  • c++的释放内存:delete[] name;//[]在于告诉delete删除的对象是单个对象还是数组。
  • 注意锻炼面向对象的思想。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
class Student {
public:
    Student(char name[],int age,int scores[],int number) {
        this->name = new char[strlen(name)+1];
        strcpy(this->name,name);
        this->age=age;
        for(int i=0; i<number; i++)
            this->scores[i]=scores[i];
        numOfCourses = number;
        cout<<"Student "<<name<<" is created (1)."<<endl;
    }
    Student(char name[], int age=18) {
        this->name = new char[strlen(name)+1];
        strcpy(this->name, name);
        this->age=age;
        numOfCourses = 0;
        cout<<"Student "<<name<<" is created (2)."<<endl;
    }
    void print() {
        cout <<name <<"," << age;
        cout << ",scores :";
        for(int i=0; i<numOfCourses; i++)
            cout << " " << scores[i];
        cout<<endl;
    }
    ~Student() {
        cout<<"Student "<<name<<" is erased."<<endl;
        delete[] name;
    }
    void changeName(char name[]) {
        delete [] this->name;
        this->name = new char[strlen(name)+1]; 
        strcpy(this->name,name);
    }
    bool compare(const Student &another) {
        double avg1, avg2;
        int i;
        avg1 = avg2 = 0;
        for(i = 0; i < numOfCourses; i++)
            avg1 += scores[i];
        for(i = 0; i < another.numOfCourses; i++)
            avg1 += another.scores[i];
        if (numOfCourses > 0)
            avg1 /= numOfCourses;
        else
            avg1 = 0;
        avg2 = another.numOfCourses == 0 ? 0 : avg2 / another.numOfCourses;
        if (fabs(avg1-avg2)<=0.001) {
            return (strcmp(name, another.name)<0);
        }
        return avg1 > avg2;
    }
private:
    char *name;
    int age;
    int scores[10];
    int numOfCourses;
};
int main() {
    freopen("in.txt","r", stdin);
    char str[10];
    int data[10];
    int age, cnt;
    cin >> str;
    cin >> age >> cnt;
    for(int i=0; i<cnt; i++)
        cin >> data[i];
    Student wang(str,age,data, cnt);
    wang.print();
    Student li("LISI",19);
    Student zhang("Zhang San");
    li.print();
    zhang.print();
    zhang.changeName("Zhang Zhang");
    zhang.print();
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

哈希表扁豆

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

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

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

打赏作者

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

抵扣说明:

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

余额充值