1.2 (C++)

Design a class School.
This class has the following member functions:
void setName(char name[])
void setAge(int year)
void operator ++ ()
EXAMPLE INPUT
SYSU
99
EXAMPLE OUTPUT
NO_NAME 0
SYSU 99
SYSU 100
主程序 (不能修改)

#include "source.cpp"
#include <iostream>
using namespace std;

void print(School & school) {
    cout << school.name << ' ' << school.age << endl;
}

int main() {
    School school;
    print(school);
    
    char name[10];
    cin >> name;
    school.setName(name);
    int age;
    cin >> age;
    school.setAge(age);
    print(school);
    
    ++ school;
    print(school);
}

我的答案
版本1

#include<string.h>
class School{
    public:
    char name[10];
    int age=0;
    
    School(){
        strcpy(name,"NO_NAME");
    }


    void setName(char name[]){
        strcpy(this->name,name);
        //this->name=name;
    }
    
    void setAge(int age){
        this->age=age;
    }
};

School operator++(School &a){

        a.age=1+a.age;
        return a;
    }

版本2

#include<string.h>
class School{
    public:
    char name[10];
    int age=0;
    
    School(){
        strcpy(name,"NO_NAME");
    }

    void setName(char name[]){
        strcpy(this->name,name);
    }
    
    void setAge(int age){
        this->age=age;
    }
    School operator++( ){
        this->age++;
    }
};

版本3

#include<string.h>
class School{
    public:
    char name[10]="NO_NAME";
    int age=0;    
    void setName(char name[]){
        strcpy(this->name,name);
    }
    void setAge(int age){
        this->age=age;
    }
    School operator++( ){
        this->age++;
    }
};
上一篇: 2.1 (C++) 下一篇: 1.1 (C++)
支持 makedown语法