Meros olish derived class


Download 23.72 Kb.
Sana20.01.2023
Hajmi23.72 Kb.
#1105252
Bog'liq
C Merosxurlik


C++ Merosxurlik (Sinf/Class)
Assalomu alaykum bugun siz bilan merosxurlik haqida gaplashamiz. Class ichida va undan tashqari foydalanish va uning qulayliklari haqida gaplashib olamiz.
Meros olish

Sinfdan meros olish uchun :belgidan foydaniladi. Quyidagi misoldaCarsinf (bola) atributlar va usullarni Vehicle sinfdan (ota-onadan) meros qilib oladi :
#include
#include
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;
}
Tuut, tuut!
Ford Mustang
"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
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;
}
Hello World. MasterSherkulov.
Ko'p meros.
Sinf shuningdek, vergul bilan ajratilgan ro'yxat yordamida bir nechta asosiy sinflardan olinishi mumkin :
#include
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;
}
Hello World. MasterSherkulov.
Hello World. MasterSherkulov.
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
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;
}
Salary: 50000
Bonus: 15000

Download 23.72 Kb.

Do'stlaringiz bilan baham:




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling