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_name
和get_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 等于我要设置的任何内容。
知道了所有这些信息,我仍然不知道什么是构造函数以及我应该将它用于什么。这很令人困惑。