Assalomu alaykum bugun siz bilan merosxurlik haqida gaplashamiz. Class ichida va undan tashqari foydalanish va uning qulayliklari haqida gaplashib olamiz.
Meros olish
- derived class (bola) - boshqa sinfdan meros qolgan sinf.
- base class (ota-ona) - meros bo'lib o'tgan sinf.
Sinfdan meros olish uchun :
belgidan foydaniladi. Quyidagi misolda, Car
sinf (bola) atributlar va usullarni Vehicle
sinfdan (ota-onadan) meros qilib oladi :
#include <iostream>
#include <string>
using namespace std;
// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};
// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};
int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
"Meros" dan qachon va qanday vaqtda foydalanish kerak?
"Meros" - bu odatda bitta class dan qayta qayta foydalanish imkoniyatini beradi. Yangi sinf yaratishda sinf attributlaridan foydalanish imkoniyati.
Ko'p darajali meros
#include <iostream>
using namespace std;
class MyClass {
public:
void myFunction() {
cout << "Hello World. MasterSherkulov." ;
}
};
class MyChild: public MyClass {
};
class MyGrandChild: public MyChild {
};
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}
Ko'p meros.
Sinf shuningdek, vergul bilan ajratilgan ro'yxat yordamida bir nechta asosiy sinflardan olinishi mumkin :
#include <iostream>
using namespace std;
class MyClass {
public:
void myFunction() {
cout << "Hello World. MasterSherkulov.\n" ;
}
};
class MyOtherClass {
public:
void myOtherFunction() {
cout << "Hello World. MasterSherkulov.\n" ;
}
};
class MyChildClass: public MyClass, public MyOtherClass {
};
int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
Meros Huquqi.
Siz Kirish xususiyatlarini aniqlash bo'limidan C ++ da uchta aniqlovchi mavjudligini bilib oldingiz . Hozirgacha biz faqat foydalanganmiz public
(sinf a'zolariga sinf tashqarisidan kirish mumkin) va private
(a'zolarga faqat sinf ichida kirish mumkin). Uchinchi spetsifikatorga protected
o'xshash private
, ammo unga meros qilib olingan klassda kirish mumkin :
#include <iostream>
using namespace std;
class Employee {
protected: // Protected access specifier
int salary;
};
class Programmer: public Employee {
public:
int bonus;
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout << "Salary: " << myObj.getSalary() << "\n";
cout << "Bonus: " << myObj.bonus << "\n";
return 0;
}