ที่นี่เราจะดูวิธีการเริ่มต้นตัวแปรสมาชิกประเภท const โดยใช้ตัวสร้าง?
ในการเริ่มต้นค่า const โดยใช้ตัวสร้าง เราต้องใช้รายการเริ่มต้น รายการ initializer นี้ใช้เพื่อเริ่มต้นสมาชิกของข้อมูลของคลาส รายชื่อสมาชิกที่จะเริ่มต้น จะมีอยู่หลังตัวสร้างหลังโคลอน สมาชิกจะถูกคั่นด้วยเครื่องหมายจุลภาค
ตัวอย่าง
#include <iostream>
using namespace std;
class MyClass{
private:
const int x;
public:
MyClass(int a) : x(a){
//constructor
}
void show_x(){
cout << "Value of constant x: " << x ;
}
};
int main() {
MyClass ob1(40);
ob1.show_x();
} ผลลัพธ์
Value of constant x: 40