如何将char*转换为Class类型?

How am I supposed to cast a char* into a Class type

本文关键字:Class 类型 转换 char      更新时间:2023-10-16

我试图将char*转换为我自己制作的类,并且似乎无法让它工作而没有错误告诉我,我根本无法将char*转换为类型Player(我的类名称)。字符指针来自指针数组char *names[i], i = any index, names[i] = one of the names,即Austin或Kyle。有了这个,我认为ichar*,但我可能错了。

我想要实现的是通过类型为Playerpush_back的向量迭代每个char* i到向量,同时将i转换为类型Player。我当然希望这足够具体,如果被问到我会澄清的。

/*
Inside of my Blakjack constructor
*/
for (int i = 0; i < numPlayers; i++) {
    //m_players is the vector of type Player
    //Player *p = new Player(names[i]);
    m_players.push_back(names[i]);
  }
/*
The Player.h File
*/
#include <vector>
class Player {
    public:
        Player(const char *name);
    private:
        int m_funds;
        char *m_name;
};
/*
The Player.cpp File
*/
#include "Player.h"
#include <iostream>
Player::Player(const char *name){
    m_name = name; //I think this will work but it's hard to tell with my Blackjack
                     constructor still giving errors
    m_funds = 100;
}

听起来像是要为字符串数组中的每个名称创建一个Player对象。

如果是这种情况,你真的不想将char *转换为Player,你想为数组中的每个char *构造一个Player。比如:

for (int i = 0; i < nameCount; i++)
{
    Player *p = new Player(names[i]);
    // Do something with p
    v.push_back(p); // ?? or something
}

这里假设你的Player类有一个构造函数,看起来像这样:

Player::Player(const char *name)

v是一个std::vector<Player>

如果你的Player类有这个构造函数,语言实际上允许将char*隐式转换为Player(当你试图将char*强制转换为Player时,这可能是你想的):

for (int i = 0; i < nameCount; i++)
{
    v.push_back(names[i]); // adds a new Player, using the name stored in names[i]
}



编辑:你的播放器类也需要一个默认构造函数:

class Player {
    public:
        Player(const char *name);
        Player() {};  // should probably initialize m_name and m_funds in here (set to 0 or something) just to be pedantic
    private:
        int m_funds;
        char *m_name;
};

这样做是为了将对象放入std::vector等容器中。

您的Player构造函数接收const char*而您的m_name成员是char*。将const char*赋值给char*是无效的

创建构造函数Player::Player(char* name).