2016-02-04 150 views
-3

我想在C++中實現類似的東西。這裏是一個C#代碼。我想盡可能避免生魚指針。輸出參數在C++傳遞參考

class Program 
{ 
    public class Foo 
    { 
     public int v1; 
     public int v2; 
     public Foo(int a, int b) 
     { 
      v1 =a; v2 =b; 
     } 
    }; 

    public class Bar 
    { 
     public static void getFoo(out Foo fooObj) 
     { 
      fooObj = new Foo(1,2); 
     } 
    }; 

    static void Main() 
    { 
     Foo fooObj = null; 
     Bar.getFoo(out fooObj); 
     Console.WriteLine("Foo.v1="+fooObj.v1); 
     Console.WriteLine("Foo.v2="+fooObj.v2); 
    } 
} 
+0

任何C++教科書或教程都應該解釋如何使用引用參數。 – Barmar

+0

@Barmar儘管如此,如果有的話,很少有人會解釋正確的做法(與Jose的答案一致)。許多人會使用原始指針或對象的引用,這些對象在功能上與C#版本相差甚遠。 –

回答

1

這裏是我試圖將C#代碼轉換爲C++。但是,一旦你運行它,你需要對如何使用這裏使用的所有功能進行適當的研究。 unique_ptr基本上會管理你的「原始」指針(這是你想要的,一旦它超出範圍就會釋放它)。我已經使用可變參數模板添加了一個改進版本,因此您可以傳遞任何類型的任意數量的參數來動態創建您的Foo類。

#include <memory> 
#include <iostream> 

class Foo 
{ 
public: 
    int v1; 
    int v2; 

    Foo(int a, int b) 
    { 
     v1 =a; v2 =b; 
    } 
}; 

class Bar 
{ 
public: 
    // This is what your function looks like in C++ 
    static void getFoo(std::unique_ptr<Foo>& fooObj) 
    { 
     fooObj = std::make_unique<Foo>(1, 2); 
    } 

    // This is a better implementation. 
    template<typename ...Args> 
    static void getFoo_improved(std::unique_ptr<Foo>& fooObj, Args&&... args) 
    { 
     fooObj = std::make_unique<Foo>(std::forward<Args>(args)...); 
    } 

    // This is the one used more often in C++ tho. 
    template<typename ...Args> 
    static std::unique_ptr<Foo> getFoo_improved_x2(Args&&... args) 
    { 
     return std::make_unique<Foo>(std::forward<Args>(args)...); 
    } 
}; 

int main() 
{ 
    std::unique_ptr<Foo> fooObj = nullptr; //nullptr is not needed tho 
    Bar::getFoo(fooObj); 

    std::unique_ptr<Foo> fooObj_alt = nullptr; //nullptr is not needed tho 
    Bar::getFoo_improved(fooObj_alt, 9, 10); 

    //This is as fast as the other two 
    auto fooObj_alt_x2 = Bar::getFoo_improved_x2(50, 60); 

    std::cout << "Foo.v1=" << fooObj->v1 << std::endl; 
    std::cout << "Foo.v2=" << fooObj->v2 << std::endl; 

    std::cout << "Foo_alt.v1=" << fooObj_alt->v1 << std::endl; 
    std::cout << "Foo_alt.v2=" << fooObj_alt->v2 << std::endl; 

    std::cout << "Foo_alt_x2.v1=" << fooObj_alt_x2->v1 << std::endl; 
    std::cout << "Foo_alt_x2.v2=" << fooObj_alt_x2->v2 << std::endl; 

    return 0; 
} 
+0

-1,代碼只是答案,沒有解釋任何東西,基本上只是拋出代碼在OP,當他們沒有嘗試 – Tas

+0

@Tas我希望有人告訴我,當我開始在C++的時候看看。有時候你只想學習如何用某種語言去做某件事,而你沒有時間去閱讀1000頁的書。 – Jts

+0

'= nullptr;'對'unique_ptr'對象的聲明是多餘的;他們開始空着。恕我直言,它使代碼更混亂。 –