Sinf yarating.
Sinf yaratish uchun class kalit so'zdan foydalaning. " MyClass" Nomli sinf yaratamiz.
class MyClass { // class
public: // ochiqlik siyosati
int myNum; // Attribute (int tipiga tegishli)
string myString; // Attribute (string tipiga tegishli)
};
Misolni tushuntirish.
class Kalit so'z MyClass deb atalgan bir sinf yaratish uchun ishlatiladi .
publicKalit so'z bir bo'lib kirish belgisi ifodalaydi. Bu degani class dan tashqarida ham attributlardan foydalanish mumkin .
Sinf ichida butun son myNum va satr o'zgaruvchisi mavjud myString. O'zgaruvchilar sinf ichida e'lon qilinganida, ular atributlar deb nomlanadi .
Nihoyat, sinf ta'rifini nuqta-vergul bilan tugating ;.
Ob'ektni yaratish.
C++ dasturlash tilida biz sinf yaratdik, MyClass nomli class yaratdik, shuning uchun bundan foydalanib obyekt yaratamiz. Ob'ektni yaratish uchun MyClasssinf nomini, so'ngra ob'ekt nomini ko'rsating.
#include
#include
using namespace std;
class MyClass {
public:
int myNum;
string myString;
};
int main() {
MyClass myObj;
myObj.myNum = 15;
myObj.myString = "Some text";
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
15
Some text
Bir nechta ob'ektlar.
Siz bitta sinfning bir nechta ob'ektlarini yaratishingiz mumkin:
#include
#include
using namespace std;
class Car {
public:
string brand;
string model;
int year;
};
int main() {
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
Do'stlaringiz bilan baham: |