建立一个名为Teacher的类,该类有以下几个私有数据成员:工龄,姓名,职务。还有公有成员函数:带参构造函数Teacher(int wa,char *n,char *duty)、不带参构造函数Teacher()、改变数据成员值函数 void SetValue(int wa,char *n,char *duty)、获取数据成员函数int GetWorkAge(),char *GetName()和char *GetDuty()。在main函数中定义一个对象并初始化,然后输出对象的信息。
#include<bits/stdc++.h>
using namespace std;
class Teacher
{
private:
int workage;
string name;
string zw;
public:
Teacher(int wa,string n,string duty) : workage(wa),name(n),zw(duty) {}
Teacher() {}
void SetValue(int wa,string n,string duty) {workage = wa;name = n;zw =duty;}
int GetWorkAge() {return workage;}
string GetName() {return name;}
string GetDuty() {return zw;}
};
int main()
{
Teacher teacher(10,"zhangsan","xiaozhang");
cout<<teacher.GetWorkAge()<<teacher.GetName()<<teacher.GetDuty()<<endl;
return 0;
}
代码如下:
#include <iostream>
#include <string>
using namespace std;
class Teacher
{
private:
int mWa;
char* mName;
char* mZw;
public:
Teacher(int wa,char* n,char* duty)
{
mWa = wa;
mName = new char[strlen(n)+1];
memcpy(mName,n,strlen(n));
mName[strlen(n)] = 0;
mZw = new char[strlen(duty)+1];
memcpy(mZw,duty,strlen(duty));
mZw[strlen(duty)] = 0;
}
Teacher()
{
mWa = 0;
mName = 0;
mZw = 0;
}
~Teacher()
{
if(mName) delete[] mName;
mName = 0;
if(mZw) delete[] mZw;
mZw = 0;
}
void SetValue(int wa,char* n,char* duty)
{
mWa = wa;
if(mName) delete[] mName;
mName = new char[strlen(n)+1];
memcpy(mName,n,strlen(n));
mName[strlen(n)] = 0;
if(mZw) delete[] mZw;
mZw = new char[strlen(duty)+1];
memcpy(mZw,duty,strlen(duty));
mZw[strlen(duty)] = 0;
}
int GetWorkAge(){return mWa;}
char *GetName(){return mName;}
char *GetDuty(){return mZw;}
};
int main()
{
Teacher tc(22,"张三","教授");
cout << tc.GetName() << " " << tc.GetWorkAge() << " " << tc.GetDuty() << endl;
return 0;
}