类的方法和对象。参考?智能指针?简单的初始化?



在过去的几天里,我一直在深入研究引用和智能指针,但我仍然不知道何时使用哪个。

特别是对于我正在尝试编写的非常简单的程序。 其中不应共享对象值,而只能修改 trought,从 X 或 Y 方法返回其类型的值。

如果我没记错的话,参考文献更容易记忆,但只指一件事。 其中,智能指针更稳定,可以重新映射以指向其他内容。

第一个问题:

对于像下面示例所示的对象进行简单更改,是否甚至需要创建引用或指针? 我想从长远来看,随着程序的复杂性增加,让但初始化的对象做它们的事情可能会产生延迟问题等......

第二个问题:

据我了解,引用对象会通过在方法中用作参数时引用对象来减轻内存上的应力,而不是将对象复制粘贴到其中? smart_ptr做同样的事情吗?

类的头文件:

-Items.h-
class Health_Potion
{
public:
int qty = 0;
static int add_health_potion(int current, int add); 
};

方法的 cpp 文件:

-Items.cpp-
int Health_Potion::add_health_potion(int current, int add)
{
int new_current = current + add;
cout << add << " potion added to your inventory.n";
cout << "Quantity available: " << new_current << "n";
return current + add;
}

主要功能:

-Main-
int main()
{
// Initializing the method to be used:
// Question: Should this also be stored into a smart_ptr or referenced to?
Health_Potion add_method;
add_method.add_health_potion;
______________________________________________
// The unique_ptr version I got:
std::unique_ptr<Health_Potion> entity(new Health_Potion); //Unique_ptr
entity -> qty = add_method.add_health_potion(rentity -> qty, roll); //returning new value to the pointer through method
______________________________________________
//The reference version I got:
Health_Potion obj1;
int & refqty = obj1.qty; //reference to object of qty created
refqty = add_method.add_health_potion(refqty, roll); //returning new value to the reference through method
}

原谅我的新手。

并感谢您抽出时间:)。

我仍然不知道何时使用哪个。

如有疑问,请使用最简单的方法。只有当最简单的方法不充分或笨拙时,才有理由考虑更复杂的事情(在这一点上,你有一个起点来弄清楚使用哪个(。

最新更新