首先设置头文件,将题目中的要求完成。
cpp
#include <iostream>
using namespace std;
class Person
{
public:
Person();
Person(string name, int id, string address);
~Person();
void setPerson(string name, int id, string address);
void setName(string name);
void setID(int id);
void setAddress(string address);
string getName();
int getID();
string getAddress();
void print(); // outPutResult
private:
string Name;
int ID;
string Address;
};
完成各个功能函数在另一个cpp中。
cpp
#include "Person.h"
using namespace std;
Person::Person()
{
Name = "S.M.Wang";
ID = 070145;
Address = "莲花路200号";
}
Person::Person(string name, int id, string address)
{
setPerson(name, id, address);
}
Person::~Person()
{
cout << "object Destructor is called" << endl;
}
void Person::setPerson(string name, int id, string address)
{
Name = name;
ID = id;
Address = address;
}
void Person::setName(string name)
{
Name = name;
}
void Person::setID(int id)
{
ID = id;
}
void Person::setAddress(string address)
{
Address = address;
}
string Person::getName()
{
return Name;
}
int Person::getID()
{
return ID;
}
string Person::getAddress()
{
return Address;
}
void Person::print()
{
cout << "姓名:" << getName() << endl;
cout << "ID:" << getID() << endl;
cout << "住址:" << getAddress() << endl;
}
最后在main调用,先设定和初始化类再执行public函数。
cpp
#include <iostream>
#include "Person.h"
using namespace std;
int main()
{
Person myPerson;
// Person myPerson("S.M.Wang", 070145, "莲花路200号");
cout << "请输入姓名:" ;
string name;
cin >> name;
cout << "请输入ID:" ;
int id;
cin >> id;
cout << "请输入住址:" ;
string address;
cin >> address;
myPerson.setName(name);
myPerson.setID(id);
myPerson.setAddress(address);
myPerson.print();
return 0;
}