我想在C++中创建一个函数来获取指向具有某些条件的类的指针。我有一个类的多个实例,由一个数字标识。根据编号,我想获得相应的实例。等价于C++中的C++
在C#中它会是这样的:
class main
{
private Example item1;
private Example item2;
private Example item3;
private Example item4;
public bool InitializeItem(int itemID)
{
bool isInitialized = false;
Example item;
if (tryGetItem(itemID, out item))
{
item = new Example(itemID);
isInitialized = true;
}
return isInitialized;
}
private bool tryGetItem(int itemID, out Example item)
{
bool canGet = false;
item = null;
switch (itemID)
{
case 1:
item = item1;
canGet = true;
break;
case 2:
item = item2;
canGet = true;
break;
case 3:
item = item3;
canGet = true;
break;
case 4:
item = item4;
canGet = true;
break;
}
return canGet;
}
}
class Example
{
int number { get; set; }
public Example(int i)
{
number = i;
}
}
但在C++我和引用和指针一点点迷惑。我读了一些教程,如this one(法语)。我理解基本的指针,但是类和功能我迷路了。
有了第一个答案,我改变了我的代码:
Example item1;
Example item2;
Example item3;
Example item4;
bool tryGetItem(int b, Example &ptr)
{
bool canGet = false;
ptr = NULL;
switch (b)
{
case 1:
ptr = item1;
canGet = true;
break;
/* etc */
}
return canGet;
}
bool InitializeItem(int id)
{
bool isInit = false;
Example ptr = NULL;
if (getParam(id, ptr))
{
ptr = Example(id);
isInit = true;
}
return isInit;
}
但它不工作。我试图调试,getParam(1, ptr)
是真的,在{..}变量ptr
被正确设置为1,但item1
不会改变。
编辑: 我不认为这是可能重复的帖子相同的问题。我不想修改tryGetItem
中的ptr
,我想用tryGetItem
使ptr
指向我的itemX
之一。在使用值为1的tryGetItem
后,修改ptr
也必须修改item1
。
搜索“通过引用传递”&'并阅读[良好的C++书](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – UnholySheep
C++作品退出与C#不同。通常像处理对象一样处理对象,而在C#中处理“int”。 C++中的对象通常不是“引用堆上的某个对象”,而更像是“对象只是对象,因为整数只是整数” –
通常,返回输出优于输出参数。 –