C ++ 类 | 构造函数w参数_6

构造函数w参数

C ++ 允许类构造函数接受参数。 创建对象时,这些参数将设置类成员的值。

让我们看一个带参数的构造函数的示例。

#include<iostream>
#include<string>
using namespace std;

class Patient
{
    private:
        string name;
    public:
        //The constructor accepts a name parameter
        Patient(string input);
        void setName(string input);
        string getName();
};

Patient::Patient(string input)
{
    //when an object is created
    //the name must be added as a parameter
    name = input;
}

void Patient::setName(string input)
{
    name = input;
}

string Patient::getName()
{
    return name;
}

以上代码保存为 main.hpp 头文件。

#include "main.hpp"

int main()
{
    //an instance of Patient is
    //instanciated with a name
    Patient p1("Tammy Smith");  
    cout<<p1.getName();
    return 0;
}

运行结果:

代码比较易懂,不过需掌握,眼神学习即可。 


编程之久除了算法和数据结构,什么也不属于我们。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值