【问题标题】:Class' methods and objects. Reference? Smart pointers? Simple initialization?类的方法和对象。参考?智能指针?简单的初始化?
【发布时间】:2020-09-01 18:01:16
【问题描述】:

过去几天我一直在研究引用和智能指针,但我仍然不知道什么时候使用。

特别是对于我正在尝试编写的非常简单的程序。 对象值不应该被共享而只被修改的地方是通过从 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】:

    我还是不知道什么时候用哪个。

    如有疑问,请使用最简单的方法。只有当最简单的方法不合适或笨拙时,才有理由考虑更复杂的方法(此时,您就有了确定使用哪种方法的起点)。

    【讨论】:

    • 嗯……很公平。我想我正在考虑目前需要什么的过程。我将从基础开始,然后从那里开始。谢谢。
    • @Erzats 和未来读者的旁注:任何对过度思考某事感到沮丧的人都应该在他们最喜欢的搜索门户中输入“过度工程”......有人需要一个告诉你它是茶壶的茶壶吗? :)
    猜你喜欢
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 2018-12-24
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多