首页 > 解决方案 > 如果可以使用 get 和 set,为什么还要使用构造函数?

问题描述

OOP 让我很头疼 :( 因为我了解构造函数的工作原理,但我不明白它们的用途。

我有一个Player看起来像这样的类:

class Player
{
private:
    std::string name;
    int health;
    int xp;
public:
    //Overloaded Constructor
    Player(std::string n, int h, int x) 
        {
        name = n;
        health = h;
        xp = x;
        }       
};

int main()
{
    Player slayer("Jimmy", 1000, 200);
    return 0;
}

在那里使用构造函数(我不知道它的作用或用途)我可以使用set_nameget_name方法来设置名称 - 并对 health 和 xp 执行相同的操作 - 然后使用函数获取名称。那么,构造函数替换函数???

如果它不替换 set & get 那么它的目的是什么?此外,我可以使用上面相同的构造函数来初始化我的属性并避免垃圾:

Player(std::string n, int h, int x) : name{n}, health{h}, xp{x} {}

但是我也可以这样做:

Player(std::string n, int h, int x) : name{n}, health{h}, xp{x} { name = n; health = h; xp = x;}

我不明白,这一切是什么意思?我知道在第一种情况下我正在初始化它,在第二种情况下我说名称 health 和 xp 等于我要设置的任何内容。

知道了所有这些信息,我仍然不知道什么是构造函数以及我应该将它用于什么。这很令人困惑。

标签: c++functionconstructordestructorclass-constructors

解决方案


构造函数在 C++ 中起着非常重要的作用。使用正确编写的构造函数,您知道对象始终是有效的。它永远不能被分配,但不知何故处于无效状态。

通常,如果您的类有一个set设置其所有状态的方法,您只需让构造函数set使用一组适当的默认值执行即可。这样您就不需要复制代码,并且您的对象具有从一开始就处于有效状态的良好属性。


推荐阅读