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

问题描述 投票:0回答:1

[最近几天我一直在研究参考书和智能指针,但我仍然不知道何时使用它。

特别是对于我要编写的非常简单的程序。在不应该共享对象值的情况下,只有修改后的对象才能通过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
}

原谅我的新手。

并且感谢您的宝贵时间:)。

c++ object methods reference smart-pointers
1个回答
2
投票

我仍然不知道何时使用它。

[如有疑问,请使用最简单的方法。只有当最简单的方法不够充分或笨拙时,才有理由考虑更复杂的事情(在这一点上,您才有一个起点来确定要使用的方法)。

© www.soinside.com 2019 - 2024. All rights reserved.