วิธีการคลาส C ++
วิธีการเรียน
เมธอดเป็นฟังก์ชันที่เป็นของคลาส
มีสองวิธีในการกำหนดฟังก์ชันที่เป็นของคลาส:
- คำจำกัดความภายในคลาส
- คำจำกัดความของคลาสภายนอก
ในตัวอย่างต่อไปนี้ เรากำหนดฟังก์ชันภายในคลาส และตั้งชื่อว่า " myMethod
"
หมายเหตุ:คุณเข้าถึงวิธีการเช่นเดียวกับที่คุณเข้าถึงแอตทริบิวต์ โดยการสร้างวัตถุของคลาสและใช้ไวยากรณ์จุด ( .
):
ตัวอย่างภายใน
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;
}
ในการกำหนดฟังก์ชันนอกนิยามคลาส คุณต้องประกาศฟังก์ชันภายในคลาส แล้วกำหนดฟังก์ชันภายนอกคลาส ทำได้โดยการระบุชื่อของคลาส ตามด้วยตัว::
ดำเนินการความละเอียดขอบเขต ตามด้วยชื่อของฟังก์ชัน:
ตัวอย่างภายนอก
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;
}
พารามิเตอร์
คุณยังสามารถเพิ่มพารามิเตอร์:
ตัวอย่าง
#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;
}