2017-10-12 101 views
-1

我想在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

+5

搜索“通过引用传递”&'并阅读[良好的C++书](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – UnholySheep

+0

C++作品退出与C#不同。通常像处理对象一样处理对象,而在C#中处理“int”。 C++中的对象通常不是“引用堆上的某个对象”,而更像是“对象只是对象,因为整数只是整数” –

+0

通常,返回输出优于输出参数。 –

回答

2

使用引用:

bool tryGetItem(int b, Example & var) 
{ 
} 

您可以使用它很简单:

int main() 
{ 
    Example var; 
    tryGetItem(42, var); 
} 

除非真有必要,因为没有其他解决方案可用,avoir在C++中使用裸指针,喜欢引用或智能指针。在你的情况下,参考是最好的选择,并会为你完美效仿out

+0

感谢您的回答。我尝试了你的解决方案,但是当我做'tryGetItem(2,var);'(指向'item2')和'var = Example(2)'时,变量'var'被正确设置为2,但'item2'不会改变。 –