简体   繁体   中英

Copy string in C++

I would like to convert this constructor's argument from const char* to std::string , but I don't know how to copy the new name to name properly.

Player::Player(const char* name) :
        level(1),life(1),strength(1),place(0){
    char* new_player_name = new char[strlen(name) + 1];
    strcpy(new_player_name, name);
    this->player_name = new_player_name;
}

Player::Player(string name) :
        level(1),life(1),strength(1),place(0){
    string new_player_name(' ',name.length() + 1); //#1
// I didn't know how to proceed 
}

The classes data-members:

class Player {
    char* player_name;
    int level;
    int life;
    int strength;
    int place;
};

Consider making player_name a std::string .

Then your constructor could start

Player::Player(const char* name) : player_name(name)
{

and you don't need to fiddle about with all those dynamically allocated char arrays.

You could change the type of name to a const std::string& too:

Player::Player(const std::string& name) : player_name(name)
{

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