C++ Method (Sinf/Class)

Method sinfga tegishli funksiyalardir. Sinfga tegishli funksiyalarni aniqlash uchun ikki yo'l mavjud.

  • Ichki sinf ta'rifi
  • Sinfdan tashqari ta'rif
#include <iostream>
using namespace std;
​
class MyClass {    
  public:               
    void myMethod() {   
      cout << "Hello World!";
    }
};
​
int main() {
  MyClass myObj;    
  myObj.myMethod();  
  return 0;
}
Hello World!

Sinf tashqarida funksiyani aniqlash uchun sinf ichida e'lon qilish kerak va keyin uni sinfdan tashqarida e'lon qilish kerak. :: sinf nomini ko'rsatish uchun ishlatiladi.

#include <iostream>
using namespace std;
​
class MyClass {         
  public:              
    void myMethod();    
};
​
​
void MyClass::myMethod() {
  cout << "Hello World!";
}
​
int main() {
  MyClass myObj;     
  myObj.myMethod(); 
  return 0;
}
Hello World!

Parametrlar.

Siz shuningdek parametrlarni qo'shishingiz mumkin:

#include <iostream>
using namespace std;
​
class Car {
  public:
    int speed(int maxSpeed);
};
​
int Car::speed(int maxSpeed) {
  return maxSpeed;
}
​
int main() {
  Car myObj;
  cout << myObj.speed(913);
  return 0;
}
913