美文网首页
(十六)C++篇-自定义类(一)

(十六)C++篇-自定义类(一)

作者: GoodTekken | 来源:发表于2022-06-27 14:24 被阅读0次

1,编写一个名为 Person 的类,表示人的名字和地址。使用 string 来保存每个元素。
2,为 Person 提供一个接受两个 string 参数的构造函数。
3,提供返回名字和地址的操作。

#include <iostream>
#include <string>

using namespace std;

class Person{
public:
    Person(const std::string &nm,const std::string &addr):name(nm),address(addr)
    {
    }
    
    std::string getName() const
    {
        return name;
    }
    
    std::string getAddress() const
    {
        return address;
    }
    
private:
    std::string name;
    std::string address;
};

int main()
{
    Person LiHong("LiHong","XiangGuang");
    Person XiaoMing("XiaoMing","GuangDong");
    cout<<LiHong.getName()<<" Live in "<<LiHong.getAddress()<<endl;
    cout<<XiaoMing.getName()<<" Live in "<<XiaoMing.getAddress()<<endl;
    return 0;
}

输出结果:

tekken@tekken:~/C++WS$ ./a.out 
LiHong Live in XiangGuang
XiaoMing Live in GuangDong

相关文章

网友评论

      本文标题:(十六)C++篇-自定义类(一)

      本文链接:https://www.haomeiwen.com/subject/ncanvrtx.html