// test.h file
class test
{ test();
~test();
public:
const tchar* m_pvariable;
struct values{
const tchar* value1;
const tchar* value2;
};
};
// test.cpp file
#include "test.h"
test::test():m_pvariable(), struct() // default value
{
}
test::~test()
{}
void test::function(int num)
{
if ( num == 1)
m_pvariable = "yes";
else
m_pvariable = "No";
values.value1 = m_pvariable;
}
问题:默认分配对我的其他代码工作正常,但我应该如何将tchar值分配给指针?
答案 0 :(得分:1)
您正在谈论的主题称为映射或关联。您正在将数字映射到字符串。
有很多解决方案:
1)switch
声明。
2)std::map
3)std::vector<std::string>
4)阵列
5)表查找。
你也可以使用if
- else
语句,但这很难看。
switch
声明示例:
int selection;
std::string text;
switch (selection)
{
case 1: text = "Yes"; break;
case 2: text = "No"; break;
default: text = "unknown"; break;
}
示例:
std::map<int, std::string> table;
table[1] = "Yes";
table[2] = "No";
int selection;
//...
std::string text = table[selection];
示例:
std::vector<std::string> table =
{ "Unknown", "Yes", "No"};
int selection = 1;
std::cout << "You chose " << table[selection] << ".\n";
示例:
const char * table[] =
{"Unknown", "Yes", "No"};
std::cout << "Text for 2 is " << table[2] << ".\n";
示例:
struct Entry
{
int key;
char * value;
};
static const Entry table[] =
{
{1, "Yes"}, // Associate 1 with "Yes"
{2, "No"}, // Associate 2 with "No"
};
static const unsigned int table_size =
sizeof(table) / sizeof(table[0]);
std::string Lookup(int key)
{
std::string text = "Unknown";
for (unsigned int i = 0; i < table_size; ++i)
{
if (table[i].key == key)
{
text = table[i].value;
break;
}
}
return text;
}
每种解决方案都有其优点和缺点。例如,可以通过在不更改代码的情况下添加到表来扩展表格外观;但是对于少量的关联来说可能是太多的代码。 switch
可能适用于少量,但对于大量或数量变化的维护噩梦。将它们作为工具箱中的工具保存并按您的需要使用。