C++ တည်ဆောက်သူများ
တည်ဆောက်သူများ
C++ ရှိ constructor သည် class တစ်ခု၏ object တစ်ခုကို ဖန်တီးသောအခါ အလိုအလျောက်ခေါ်သည့် အထူးနည်းလမ်းတစ်ခု ဖြစ်သည်။
constructor တစ်ခုဖန်တီးရန်၊ class နှင့်တူသောအမည်ကိုသုံးပါ၊ ထို့နောက် ကွင်းစဥ်များဖြင့် ()
:
ဥပမာ
class MyClass { // The class
public:
// Access specifier
MyClass() {
// Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass (this will call
the constructor)
return 0;
}
မှတ်ချက်- constructor တွင် class နှင့် တူညီသော အမည် ရှိပြီး ၎င်းသည် အမြဲတမ်း public
ဖြစ်ပြီး ၎င်းတွင် မည်သည့် return value မှ မရှိပါ။
တည်ဆောက်သူ ကန့်သတ်ချက်များ
တည်ဆောက်သူများသည် attribute များအတွက် ကနဦးတန်ဖိုးများကို သတ်မှတ်ရာတွင် အသုံးဝင်နိုင်သည် (ပုံမှန်လုပ်ဆောင်ချက်များကဲ့သို့) ကန့်သတ်ချက်များကိုလည်း ယူနိုင်သည်။
အောက်ပါ class တွင် brand
, model
နှင့် year
attribute များ , နှင့် မတူညီသော parameters များပါရှိသော constructor တစ်ခုရှိသည်။ constructor အတွင်းတွင် ကျွန်ုပ်တို့သည် constructor parameters ( brand=x
, etc) နှင့်ညီသော attribute များကို သတ်မှတ်ပေးသည်။ constructor ကိုခေါ်သောအခါ (Class ၏ object တစ်ခုကိုဖန်တီးခြင်းဖြင့်) constructor ထံသို့ parameters များပေးပို့ပြီး သက်ဆိုင်ရာ attribute များ၏တန်ဖိုးကို တူညီအောင်သတ်မှတ်ပေးမည်ဖြစ်ပါသည်။
ဥပမာ
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z)
{ // Constructor with parameters
brand =
x;
model = y;
year = z;
}
};
int main() {
//
Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang",
1969);
// Print values
cout << carObj1.brand << " "
<< carObj1.model << " " << carObj1.year << "\n";
cout <<
carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
လုပ်ဆောင်ချက်များကဲ့သို့ပင်၊ constructors များကို class ပြင်ပတွင် သတ်မှတ်နိုင်သည်။ ပထမဦးစွာ၊ class အတွင်းရှိ constructor ကိုကြေငြာပြီး class ၏အမည်ကိုသတ်မှတ်ခြင်းဖြင့်၊ ၎င်းနောက်တွင် scope resolution ::
operator ဖြင့်၊ ထို့နောက် constructor ၏အမည် (ထို class နှင့်တူညီသည်) ဖြင့်၎င်းကို class ၏ပြင်ပတွင်သတ်မှတ်ပါ။
ဥပမာ
class Car { // The class
public: // Access
specifier
string brand; // Attribute
string model; // Attribute
int year;
// Attribute
Car(string x, string y, int z); //
Constructor declaration
};
// Constructor definition outside the
class
Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
int main() {
// Create
Car objects and call the constructor with different values
Car
carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " <<
carObj1.model << " " << carObj1.year << "\n";
cout <<
carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}