C++之Person类

首先设置头文件,将题目中的要求完成。

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;
}
相关推荐
鱼跃鹰飞25 分钟前
Leetcode会员尊享100题:270.最接近的二叉树值
数据结构·算法·leetcode
Queenie_Charlie31 分钟前
小陶的疑惑2
数据结构·c++·树状数组
无小道1 小时前
Qt——QWidget
开发语言·qt
时艰.1 小时前
Java 并发编程之 CAS 与 Atomic 原子操作类
java·开发语言
梵刹古音1 小时前
【C语言】 函数基础与定义
c语言·开发语言·算法
筵陌2 小时前
算法:模拟
算法
梵刹古音2 小时前
【C语言】 结构化编程与选择结构
c语言·开发语言·嵌入式
Yvonne爱编码2 小时前
JAVA数据结构 DAY3-List接口
java·开发语言·windows·python
一方_self2 小时前
了解和使用python的click命令行cli工具
开发语言·python
南宫码农2 小时前
我的电视 - Android原生电视直播软件 完整使用教程
android·开发语言·windows·电视盒子