vault backup: 2026-04-16 09:11:26
This commit is contained in:
@@ -52,9 +52,6 @@ class Pokemon {
|
||||
public: // visibility modifier
|
||||
int exp;
|
||||
int level;
|
||||
int attack;
|
||||
int defense;
|
||||
int speed;
|
||||
int hp;
|
||||
|
||||
void upgrade(int gainedExp) {
|
||||
@@ -67,10 +64,97 @@ public: // visibility modifier
|
||||
}
|
||||
|
||||
int main() {
|
||||
Pokemon fukano = {3600, 1, 400, 400, 20, 1200};
|
||||
Pokemon fukano = {3600, 1, 1200};
|
||||
cout << "Exp of fukano: " << fukano.exp << endl;
|
||||
fukano.upgrade(400);
|
||||
cout << "Exp of fukano: " << fukano.exp << endl;
|
||||
}
|
||||
```
|
||||
|
||||
### Scope Modifiers
|
||||
If we want to hide data beyond the class itself we can use the `private` visibility modifier:
|
||||
|
||||
```C++
|
||||
class Pokemon {
|
||||
public:
|
||||
string name;
|
||||
|
||||
private:
|
||||
int exp;
|
||||
int level;
|
||||
int hp;
|
||||
|
||||
public:
|
||||
void upgrade(int gainedExp) {
|
||||
exp += gainedExp;
|
||||
if (exp >= 4000) {
|
||||
exp -= 4000;
|
||||
level += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
Pokemon fukano = {3600, 1, 1200};
|
||||
fukano.upgrade(400); // this is OK
|
||||
fukano.exp += 400; // this is not OK
|
||||
}
|
||||
```
|
||||
|
||||
### Getters and Setters
|
||||
_Getters and Setters_ allow **controlling the change** like:
|
||||
- ensuring a number is in a range
|
||||
- update depending parameters (like level with exp)
|
||||
|
||||
```c++
|
||||
class Pokemon {
|
||||
// ...
|
||||
public:
|
||||
void setExp() { /*...*/ }
|
||||
int getExp() { /*...*/ }
|
||||
}
|
||||
```
|
||||
|
||||
### Constructors
|
||||
|
||||
Given the class:
|
||||
```C++
|
||||
class Pokemon {
|
||||
private:
|
||||
int exp;
|
||||
int level;
|
||||
}
|
||||
```
|
||||
|
||||
We can create a new instance using the _basic constructor_:
|
||||
```C++
|
||||
class Pokemon {
|
||||
// ...
|
||||
public:
|
||||
// Default constructor: allows Pokemon <name>; -> exp = 0, level = 0;
|
||||
Pokemon(): exp(0), level(0) {};
|
||||
// or
|
||||
Pokemon(0, 0);
|
||||
|
||||
// Base constructor
|
||||
Pokemon(int e, int l) {
|
||||
exp = e;
|
||||
level = l;
|
||||
}
|
||||
// or as
|
||||
Pokemon(int e, int l): exp(e), level(l) {};
|
||||
}
|
||||
|
||||
int main() {
|
||||
Pokemon fukano(3600, 1);
|
||||
}
|
||||
```
|
||||
|
||||
We can also create an instance as a copy of another object of the _same class_:
|
||||
```C++
|
||||
class Pokemon {
|
||||
// ...
|
||||
public:
|
||||
Pokemon(const Pokemon& p)
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user