简体   繁体   中英

How dynamically in the parameterized constructor?

i wnat this object"name_of_pro"is allocated dynamically in the parameterized constructor. 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 .

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.

~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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM