C++实现get与set

相信学过JAVA的对类的get和set方法一定不陌生,现在用C++来实现get和set方法。

编写一个学生类,成员包括姓名,学号,年龄(默认值23),对上面3个成员分别都有设置值和取值的方法

头文件Student.h

#pragma once
#include<iostream>
using namespace std;
#ifndef STUDENT_H_
#define STUDENT_H_
class Student
{
public:
    Student();
    ~Student();
    void setName(char* name);
    void setNum(char* num);
    void setAge(int age);
    char* getName();
    char* getNum();
    int getAge();

private:
    char* _name;
    char* _num;
    int _age;
};

函数实现Student.cpp

#include"stdafx.h"
#include "Student.h"

Student::Student()
{
    _name = new char[10];
    _num = new char[10];
    strcpy(_name, " ");
    strcpy(_num, " ");
    _age = 23;
}

Student::~Student()
{
    delete [] _name;
    delete [] _num;
}

void Student::setName(char* name)
{
    if(name == NULL)
        return ;
    strcpy(_name, name);
}

void Student::setNum(char* num)
{
    if (num == NULL)
        return;
    strcpy(_num,num);
}

void Student::setAge(int age)
{
    _age = age;
}

char* Student::getName()
{
    return _name;
}

char* Student::getNum()
{
    return _num;
}

int Student::getAge()
{
    return _age;
}

int main()
{
    Student a;
    a.setAge(10);
    a.setName("libai");
    a.setNum("12306");
    Student b;
    cout << a.getName() << endl;
    cout << a.getNum() << endl;
    cout << a.getAge() << endl;
    cout << b.getName() << endl;
    cout << b.getNum() << endl;
    cout << b.getAge() << endl;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值