如何将char*转换为Class类型?
How am I supposed to cast a char* into a Class type
我试图将char*转换为我自己制作的类,并且似乎无法让它工作而没有错误告诉我,我根本无法将char*
转换为类型Player
(我的类名称)。字符指针来自指针数组char *names[i], i = any index, names[i] = one of the names
,即Austin或Kyle。有了这个,我认为i
是char*
,但我可能错了。
我想要实现的是通过类型为Player
和push_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).
相关文章:
- '{'标记之前的预期类名,然后在预声明时无效使用不完整的类型'class class_name'
- C2011 'CMemDC':Visual Studio 2019中的'class'类型重新定义
- C++错误:"class name"之前的预期类型说明符
- "class":非法使用此类型作为表达式 如何解决?
- 如何配置 Doxygen 以在"Class Index"中包含类的类型定义?
- 无法将'Class::operator=='从"布尔"类型(类::)(类*)转换为"布尔"类型
- 获取生成错误:错误 C2011:'ProfileSettings':'class'类型重定义
- 'class MyClass' 在尝试定义静态结构实例时不会命名类型
- 'inherit class'中类型 'template class' 引用的初始化无效
- C++模板: <class> 不命名类型
- Visual Studio 2015 C2011 'Class' 类型重定义
- 错误 C2011:'SelectorBox':'class'类型重定义
- "日期":'class'类型重新定义:错误(日历.cpp文件错误)
- 从QString到Class类型
- C++ 'class'类型重新定义
- 'class'类型重定义/基类未定义
- Push_back到class类型的向量中
- C++ 代码错误(非法成员初始化、'class'类型重定义、'return':无法转换)
- 为什么C++不能用 "super class" 类型的右值初始化 "derived class" 类型的变量?
- 如何将char*转换为Class类型?