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;
}
相关推荐
吴声子夜歌13 小时前
Java——显示条件
java·开发语言
有味道的男人13 小时前
1688 商品价格 API:阶梯价、代发价、批发价实时查询
开发语言·windows·python
范范@14 小时前
python基础-for循环和列表
开发语言·python
小白学大数据14 小时前
Python 爬虫动态 JS 渲染与无头浏览器实战选型指南
开发语言·javascript·爬虫·python
朔北之忘 Clancy14 小时前
2026 年 3 月青少年软编等考 C 语言一级真题解析
c语言·开发语言·c++·学习·青少年编程·题解·一级
Aaron158814 小时前
RFSOC+VU13P/VU9P+GPU多通道同步一体化解决方案
人工智能·嵌入式硬件·算法·matlab·fpga开发·硬件架构·基带工程
佳xuan14 小时前
模型训练之爬取数据
开发语言·python
之歆14 小时前
DAY_10 JavaScript 深度解析:原型链 · 引用类型 · 内置对象 · 数组方法全攻略(上)
开发语言·javascript·ecmascript
zmzb010314 小时前
Python课后习题训练记录Day122
开发语言·python
陳土14 小时前
R语言jiebaR包使用摘要
开发语言·r语言