کلاس‌ها و اشیاء

آشنایی با کلاس‌ها و اشیاء در C++، تعریف کلاس و ایجاد اشیاء

کلاس‌ها و اشیاء

کلاس‌ها (Classes) الگوهایی برای ایجاد اشیاء (Objects) هستند. برنامه‌نویسی شیءگرا (OOP) روشی برای سازماندهی کد با استفاده از کلاس‌ها و اشیاء است.

تعریف کلاس

class ClassName {
    // اعضای کلاس
};

مثال پایه

class Car {
public:
    string brand;
    string model;
    int year;
    
    void drive() {
        cout << brand << " " << model << " در حال حرکت است" << endl;
    }
};

int main() {
    Car myCar;
    myCar.brand = "Toyota";
    myCar.model = "Corolla";
    myCar.year = 2020;
    myCar.drive();
    return 0;
}

توابع عضو (Member Functions)

class Rectangle {
public:
    double width;
    double height;
    
    double area() {
        return width * height;
    }
    
    double perimeter() {
        return 2 * (width + height);
    }
};

سازنده‌ها (Constructors)

سازنده تابعی است که هنگام ایجاد شیء اجرا می‌شود.

class Person {
public:
    string name;
    int age;
    
    // سازنده
    Person(string n, int a) {
        name = n;
        age = a;
    }
    
    void display() {
        cout << "نام: " << name << ", سن: " << age << endl;
    }
};

int main() {
    Person person("علی", 25);
    person.display();
    return 0;
}

سازنده پیش‌فرض

class Person {
public:
    string name;
    int age;
    
    // سازنده پیش‌فرض
    Person() {
        name = "ناشناس";
        age = 0;
    }
    
    // سازنده با پارامتر
    Person(string n, int a) {
        name = n;
        age = a;
    }
};

دسترسی به اعضا (Access Specifiers)

دسترسیتوضیح
publicاز هر جا قابل دسترسی
privateفقط داخل کلاس
protectedداخل کلاس و کلاس‌های مشتق
class BankAccount {
private:
    double balance;
    
public:
    string accountNumber;
    
    BankAccount(string accNum, double initialBalance) {
        accountNumber = accNum;
        balance = initialBalance;
    }
    
    void deposit(double amount) {
        balance += amount;
    }
    
    bool withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
            return true;
        }
        return false;
    }
    
    double getBalance() {
        return balance;
    }
};

بهترین شیوه‌ها

نکات مهم

این مبحث بخشی از دوره آموزش کامل C++ است.

ابزارهای مرتبط