Metody klas C++
Metody klas
Metody to funkcje należące do klasy.
Istnieją dwa sposoby definiowania funkcji należących do klasy:
- Wewnątrz definicji klasy
- Poza definicją klasy
W poniższym przykładzie definiujemy funkcję wewnątrz klasy i nazywamy ją " myMethod
".
Uwaga: masz dostęp do metod tak samo, jak dostęp do atrybutów; tworząc obiekt klasy i używając składni z kropką ( .
):
Przykład wewnętrzny
class MyClass { // The class
public:
// Access specifier
void myMethod() { // Method/function
defined inside the
class
cout << "Hello World!";
}
};
int main() {
MyClass
myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Aby zdefiniować funkcję poza definicją klasy, musisz zadeklarować ją wewnątrz klasy, a następnie zdefiniować poza klasą. Odbywa się to poprzez określenie nazwy klasy, po której następuje ::
operator rozpoznawania zakresu, a następnie nazwa funkcji:
Przykład zewnętrzny
class MyClass { // The class
public:
// Access specifier
void myMethod(); // Method/function
declaration
};
// Method/function definition outside the class
void
MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass
myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Parametry
Możesz również dodać parametry:
Przykład
#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int Car::speed(int maxSpeed) {
return maxSpeed;
}
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); //
Call the method with an argument
return 0;
}