這裏是我試圖將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;
}
來源
2016-02-04 03:55:47
Jts
任何C++教科書或教程都應該解釋如何使用引用參數。 – Barmar
@Barmar儘管如此,如果有的話,很少有人會解釋正確的做法(與Jose的答案一致)。許多人會使用原始指針或對象的引用,這些對象在功能上與C#版本相差甚遠。 –