构造函数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;
}
运行结果:
代码比较易懂,不过需掌握,眼神学习即可。
编程之久除了算法和数据结构,什么也不属于我们。