c++ - 如果可以使用 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_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 等于我要设置的任何内容。
知道了所有这些信息,我仍然不知道什么是构造函数以及我应该将它用于什么。这很令人困惑。
解决方案
构造函数在 C++ 中起着非常重要的作用。使用正确编写的构造函数,您知道对象始终是有效的。它永远不能被分配,但不知何故处于无效状态。
通常,如果您的类有一个set
设置其所有状态的方法,您只需让构造函数set
使用一组适当的默认值执行即可。这样您就不需要复制代码,并且您的对象具有从一开始就处于有效状态的良好属性。
推荐阅读
- tensorflow - TensorFlow 形状不匹配
- c# - EF6 - 多对一关系不起作用
- android - 将带有参数的 Firebase 动态链接连接到云函数以在 React Native 应用程序中重置用户密码
- javascript - 如何验证表单中的隐藏输入字段/更改验证行为?
- vue.js - 如果 Vue 中一个路径包含另一个路径,则导航栏一次选择两个抽屉
- git - 终端中提交的名称在github中不同
- node.js - 无法将 React-Bootstrap 与 Expo 一起使用(无法解析模块 react/jsx-runtime)
- java - Intellij 中的控制台日志格式已更改
- terraform - 尝试创建 azure 存储帐户并使用它来存储 terraform 状态文件
- python - 使用 statsmodels.tsa.seasonal.seasonal_decompose 分解营销效果