用C ++复制字符串

时间:2018-06-18 15:27:22

标签: c++ string

我想将此构造函数的参数从const char*转换为std::string,但我不知道如何将新名称复制到名称正确。

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 
}

类data-members:

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

1 个答案:

答案 0 :(得分:7)

考虑将std::string设为Player::Player(const char* name) : player_name(name) {

然后你的构造函数可以启动

char

并且您不需要动摇所有动态分配的name数组。

您也可以将const std::string&的类型更改为Player::Player(const std::string& name) : player_name(name) {

altair