相信学过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;
}