[英]How dynamically in the parameterized constructor?
i wnat this object"name_of_pro"is allocated dynamically in the parameterized constructor. 我在参数化构造函数中动态分配了该对象“ name_of_pro”。 i am trying but i think is not true
我正在尝试,但我认为不是真的
---------------------------------------... ---------------------------------------...
class employee{
string name, ID, *name_of_pro;
int age ;
float salary ;
public:
employee(){};
employee ( string n,int ag, float sa , string name_pro){ // constructor. parameterized
name=n;
age=ag;
salary=sa;
name_of_pro=new string;
}
i hope help plz. 希望对您有所帮助。
I'm not exactly sure if I understand your question, but I think what you might mean is that you want to have name_of_pro
be a copy of name_pro
. 我不确定是否能理解您的问题,但是我想您可能想说的是要让
name_of_pro
成为name_pro
的副本。
employee ( string n, int ag, float sa , string name_pro){
name=n;
age=ag;
salary=sa;
name_of_pro=new string(name_pro); // You can make a pointer to a copy this way
}
You just need to make sure you delete the string name_of_pro
in the destructor if this is what you want to do. 如果您要执行此操作,则只需确保删除析构函数中的字符串
name_of_pro
。
~employee() {
delete name_of_pro;
}
What may be even easier is an initialization list instead of all of the simple assignments. 甚至更容易的是初始化列表,而不是所有简单的分配。
employee ( string name, int age, float salary , string name_pro) :
name(name), age(age), salary(salary), name_of_pro(new string(name_pro)) {
}
Let me know if this doesn't answer your question. 让我知道这是否不能回答您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.