面向objectprogrammingBasics

LearningC++ classes and objects, encapsulation, inheritance and polymorphism - core concepts

返回tutoriallist

1. 面向objectprogrammingoverview

1.1 what is 面向objectprogramming

面向objectprogramming (Object-Oriented programming, 简称OOP) is aprogramming范式, 它将data and operationdata methodencapsulation in 一起, 形成object. 面向objectprogramming core思想 is 将现实世界in 事物abstraction for object, throughobject之间 交互来implementation程序 functions.

and 传统 过程式programming相比, 面向objectprogramming具 has 以 under 优点:

  • encapsulation性: 将data and methodencapsulation in 一起, 隐藏implementation细节, 只暴露必要 interface.
  • inheritance性: 允许creation new classinheritance现 has class property and method, improvingcode reusability.
  • polymorphism性: 允许不同class object for 同一message做出不同 response, improvingcode flexible性.
  • abstraction性: 将 complex 现实世界abstraction for simple objectmodel, improvingcode 可maintenance性.

1.2 面向objectprogramming basicconcepts

  • class (Class) : class is object 蓝graph or 模板, 定义了object property and method.
  • object (Object) : object is class instance, 具 has class定义 property and method.
  • property (Attribute) : property is object status, 通常 is classin 成员variable.
  • method (Method) : method is object behavior, 通常 is classin 成员function.
  • encapsulation (Encapsulation) : 将data and methodencapsulation in 一起, 隐藏implementation细节.
  • inheritance (Inheritance) : creation new classinheritance现 has class property and method.
  • polymorphism (Polymorphism) : 不同class object for 同一message做出不同 response.
  • abstraction (Abstraction) : 隐藏 complex implementation细节, 只暴露必要 interface.

2. classes and objects

2.1 class 定义

in C++in, class 定义usingclass关键字. class 定义includingclass名, 访问修饰符, 成员variable and 成员function.

class Person {
private:
    string name;
    int age;
public:
    // constructfunction
    Person(string n, int a) {
        name = n;
        age = a;
    }
    
    // 成员function
    void setName(string n) {
        name = n;
    }
    
    string getName() {
        return name;
    }
    
    void setAge(int a) {
        if (a > 0) {
            age = a;
        }
    }
    
    int getAge() {
        return age;
    }
    
    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

2.2 访问修饰符

C++providing了三种访问修饰符, 用于控制class成员 访问permission:

2.2.1 private (私 has )

私 has 成员只能 in class in 部访问, out 部code不能直接访问.

2.2.2 public (公 has )

公 has 成员可以 in 任何地方访问, is class and out 部code interface.

2.2.3 protected (保护)

保护成员可以 in class in 部 and forkclassin访问, out 部code不能直接访问.

2.3 object creation and using

in C++in, object creation has 两种方式: 栈 on creation and 堆 on creation.

#include <iostream>
#include <string>

using namespace std;

class Person {
private:
    string name;
    int age;
public:
    // constructfunction
    Person(string n, int a) {
        name = n;
        age = a;
    }
    
    // 成员function
    void setName(string n) {
        name = n;
    }
    
    string getName() {
        return name;
    }
    
    void setAge(int a) {
        if (a > 0) {
            age = a;
        }
    }
    
    int getAge() {
        return age;
    }
    
    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    // 栈 on creationobject
    Person p1("Alice", 25);
    p1.display();
    
    // modifyobjectproperty
    p1.setName("Bob");
    p1.setAge(30);
    p1.display();
    
    // 堆 on creationobject
    Person* p2 = new Person("Charlie", 35);
    p2->display();
    
    // modifyobjectproperty
    p2->setName("David");
    p2->setAge(40);
    p2->display();
    
    // 释放堆 on  object
    delete p2;
    
    return 0;
}

2.4 constructfunction and 析构function

2.4.1 constructfunction

constructfunction is a特殊 成员function, 用于初始化object. constructfunction 名称 and class名相同, 没 has 返回class型, 可以 has parameter.

class Person {
private:
    string name;
    int age;
public:
    // 默认constructfunction
    Person() {
        name = "Unknown";
        age = 0;
    }
    
    // 带parameter constructfunction
    Person(string n) {
        name = n;
        age = 0;
    }
    
    // 带 many 个parameter constructfunction
    Person(string n, int a) {
        name = n;
        age = a;
    }
    
    // 成员function
    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    Person p1;          // using默认constructfunction
    Person p2("Alice");  // using带一个parameter constructfunction
    Person p3("Bob", 25); // using带两个parameter constructfunction
    
    p1.display();
    p2.display();
    p3.display();
    
    return 0;
}

2.4.2 析构function

析构function is a特殊 成员function, 用于cleanobject占用 resource. 析构function 名称 is class名 before 加波浪号 (~) , 没 has parameter, 没 has 返回class型.

class Person {
private:
    string name;
    int age;
    char* address;
public:
    // constructfunction
    Person(string n, int a, string addr) {
        name = n;
        age = a;
        address = new char[addr.length() + 1];
        strcpy(address, addr.c_str());
        cout << "Constructor called for " << name << endl;
    }
    
    // 析构function
    ~Person() {
        delete[] address;
        cout << "Destructor called for " << name << endl;
    }
    
    // 成员function
    void display() {
        cout << "Name: " << name << ", Age: " << age << ", Address: " << address << endl;
    }
};

int main() {
    {
        Person p("Alice", 25, "123 Main St");
        p.display();
    } // 作用域结束, 析构function被调用
    
    cout << "Outside the block" << endl;
    
    return 0;
}

3. encapsulation

3.1 encapsulation concepts

encapsulation is 面向objectprogramming corefeatures之一, 它将data and operationdata methodencapsulation in 一起, 隐藏implementation细节, 只暴露必要 interface. encapsulation 主要目 is 保护data security性 and integrity, 防止 out 部code随意modifyobject in 部status.

3.2 encapsulation implementation

in C++in, encapsulationthrough访问修饰符来implementation. 通常, 我们将成员variable声明 for private, 将成员function声明 for public, throughpublic成员function来访问 and modifyprivate成员variable.

class BankAccount {
private:
    string accountNumber;
    string accountHolder;
    double balance;
public:
    // constructfunction
    BankAccount(string accNum, string accHolder, double initialBalance) {
        accountNumber = accNum;
        accountHolder = accHolder;
        if (initialBalance >= 0) {
            balance = initialBalance;
        } else {
            balance = 0;
        }
    }
    
    // 存款
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            cout << "Deposit successful. New balance: " << balance << endl;
        } else {
            cout << "Invalid deposit amount." << endl;
        }
    }
    
    // 取款
    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            cout << "Withdrawal successful. New balance: " << balance << endl;
        } else {
            cout << "Invalid withdrawal amount or insufficient balance." << endl;
        }
    }
    
    // query余额
    double getBalance() {
        return balance;
    }
    
    // 显示accountinformation
    void display() {
        cout << "Account Number: " << accountNumber << endl;
        cout << "Account Holder: " << accountHolder << endl;
        cout << "Balance: " << balance << endl;
    }
};

int main() {
    BankAccount acc("123456", "Alice", 1000.0);
    acc.display();
    
    acc.deposit(500.0);
    acc.withdraw(200.0);
    acc.withdraw(1500.0); // 尝试取超过余额 钱
    
    cout << "Final balance: " << acc.getBalance() << endl;
    
    return 0;
}

4. inheritance

4.1 inheritance concepts

inheritance is 面向objectprogramming 另一个corefeatures, 它允许creation new class (forkclass) inheritance现 has class (基class) property and method. inheritance 主要目 is improvingcode reusability, reducingcode 冗余.

4.2 inheritance implementation

in C++in, inheritancethrough以 under 语法implementation:

class BaseClass {
    // 基class成员
};

class DerivedClass : accessSpecifier BaseClass {
    // forkclass成员
};

其in, accessSpecifier is 访问修饰符, 可以 is public, protected or private, 用于控制基class成员 in forkclassin 访问permission.

#include <iostream>
#include <string>

using namespace std;

// 基class
class Person {
protected:
    string name;
    int age;
public:
    // constructfunction
    Person(string n, int a) {
        name = n;
        age = a;
    }
    
    // 成员function
    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

// forkclass
class Student : public Person {
private:
    string studentID;
    string major;
public:
    // constructfunction
    Student(string n, int a, string id, string m) : Person(n, a) {
        studentID = id;
        major = m;
    }
    
    // 成员function
    void display() {
        Person::display(); // 调用基class displayfunction
        cout << "Student ID: " << studentID << ", Major: " << major << endl;
    }
    
    void study() {
        cout << name << " is studying " << major << endl;
    }
};

// forkclass
class Teacher : public Person {
private:
    string teacherID;
    string subject;
public:
    // constructfunction
    Teacher(string n, int a, string id, string s) : Person(n, a) {
        teacherID = id;
        subject = s;
    }
    
    // 成员function
    void display() {
        Person::display(); // 调用基class displayfunction
        cout << "Teacher ID: " << teacherID << ", Subject: " << subject << endl;
    }
    
    void teach() {
        cout << name << " is teaching " << subject << endl;
    }
};

int main() {
    // creationStudentobject
    Student s("Alice", 20, "S12345", "Computer Science");
    s.display();
    s.study();
    
    cout << endl;
    
    // creationTeacherobject
    Teacher t("Bob", 35, "T67890", "Mathematics");
    t.display();
    t.teach();
    
    return 0;
}

4.3 inheritance class型

C++support三种inheritance方式, 根据访问修饰符 不同:

4.3.1 公 has inheritance (public)

  • 基class public成员 in forkclassin仍然 is public
  • 基class protected成员 in forkclassin仍然 is protected
  • 基class private成员 in forkclassin不可访问

4.3.2 保护inheritance (protected)

  • 基class public成员 in forkclassin变 for protected
  • 基class protected成员 in forkclassin仍然 is protected
  • 基class private成员 in forkclassin不可访问

4.3.3 私 has inheritance (private)

  • 基class public成员 in forkclassin变 for private
  • 基class protected成员 in forkclassin变 for private
  • 基class private成员 in forkclassin不可访问

5. polymorphism

5.1 polymorphism concepts

polymorphism is 面向objectprogramming 第三个corefeatures, 它允许不同class object for 同一message做出不同 response. polymorphism 主要目 is improvingcode flexible性 and 可scale性.

5.2 polymorphism implementation

in C++in, polymorphismthrough虚function (virtual function) and function重写 (override) 来implementation.

5.2.1 虚function

虚function is in 基classin声明 , usingvirtual关键字标记 成员function. 虚function允许forkclass重写 (override) 基class function, implementationpolymorphism.

#include <iostream>
#include <string>

using namespace std;

// 基class
class Shape {
public:
    // 虚function
    virtual void draw() {
        cout << "Drawing a shape" << endl;
    }
    
    // 虚析构function
    virtual ~Shape() {
        cout << "Destructing Shape" << endl;
    }
};

// forkclass
class Circle : public Shape {
public:
    // 重写基class 虚function
    void draw() override {
        cout << "Drawing a circle" << endl;
    }
    
    ~Circle() {
        cout << "Destructing Circle" << endl;
    }
};

// forkclass
class Rectangle : public Shape {
public:
    // 重写基class 虚function
    void draw() override {
        cout << "Drawing a rectangle" << endl;
    }
    
    ~Rectangle() {
        cout << "Destructing Rectangle" << endl;
    }
};

// forkclass
class Triangle : public Shape {
public:
    // 重写基class 虚function
    void draw() override {
        cout << "Drawing a triangle" << endl;
    }
    
    ~Triangle() {
        cout << "Destructing Triangle" << endl;
    }
};

int main() {
    // creation基class指针array
    Shape* shapes[3];
    
    // 用forkclassobject初始化基class指针
    shapes[0] = new Circle();
    shapes[1] = new Rectangle();
    shapes[2] = new Triangle();
    
    // polymorphism: through基class指针调用forkclass function
    for (int i = 0; i < 3; i++) {
        shapes[i]->draw();
    }
    
    // 释放memory
    for (int i = 0; i < 3; i++) {
        delete shapes[i];
    }
    
    return 0;
}

5.3 abstractionclass and 纯虚function

abstractionclass is a不能instance化 class, 它package含至 few 一个纯虚function. 纯虚function is in 基classin声明 , 没 has implementation 虚function, using= 0标记.

#include <iostream>
#include <string>

using namespace std;

// abstractionclass
class Shape {
public:
    // 纯虚function
    virtual void draw() = 0;
    
    // 普通虚function
    virtual void displayInfo() {
        cout << "This is a shape" << endl;
    }
    
    // 虚析构function
    virtual ~Shape() {
        cout << "Destructing Shape" << endl;
    }
};

// forkclass
class Circle : public Shape {
private:
    double radius;
public:
    // constructfunction
    Circle(double r) {
        radius = r;
    }
    
    // implementation纯虚function
    void draw() override {
        cout << "Drawing a circle with radius " << radius << endl;
    }
    
    // 重写普通虚function
    void displayInfo() override {
        cout << "This is a circle with radius " << radius << endl;
    }
    
    ~Circle() {
        cout << "Destructing Circle" << endl;
    }
};

// forkclass
class Rectangle : public Shape {
private:
    double width;
    double height;
public:
    // constructfunction
    Rectangle(double w, double h) {
        width = w;
        height = h;
    }
    
    // implementation纯虚function
    void draw() override {
        cout << "Drawing a rectangle with width " << width << " and height " << height << endl;
    }
    
    // 重写普通虚function
    void displayInfo() override {
        cout << "This is a rectangle with width " << width << " and height " << height << endl;
    }
    
    ~Rectangle() {
        cout << "Destructing Rectangle" << endl;
    }
};

int main() {
    // creation基class指针
    Shape* shape1 = new Circle(5.0);
    Shape* shape2 = new Rectangle(4.0, 6.0);
    
    // polymorphism
    shape1->draw();
    shape1->displayInfo();
    
    cout << endl;
    
    shape2->draw();
    shape2->displayInfo();
    
    // 释放memory
    delete shape1;
    delete shape2;
    
    return 0;
}

实践case: graph形class层次structure

design一个graph形class层次structure, includingabstraction基classShape and forkclassCircle, Rectangle, Triangle, implementationpolymorphism.

requirementsanalysis

  • creationabstraction基classShape, package含纯虚functiondraw() and calculateArea()
  • creationforkclassCircle, implementationdraw() and calculateArea()function
  • creationforkclassRectangle, implementationdraw() and calculateArea()function
  • creationforkclassTriangle, implementationdraw() and calculateArea()function
  • in 主functionin, creation不同graph形 object, through基class指针调用虚function, implementationpolymorphism

referencecode

#include <iostream>
#include <cmath>

using namespace std;

// abstraction基class
class Shape {
public:
    // 纯虚function
    virtual void draw() = 0;
    virtual double calculateArea() = 0;
    
    // 虚析构function
    virtual ~Shape() {
        cout << "Destructing Shape" << endl;
    }
};

// forkclass: 圆形
class Circle : public Shape {
private:
    double radius;
public:
    // constructfunction
    Circle(double r) {
        radius = r;
    }
    
    // implementation纯虚function
    void draw() override {
        cout << "Drawing a circle with radius " << radius << endl;
    }
    
    double calculateArea() override {
        return M_PI * radius * radius;
    }
    
    ~Circle() {
        cout << "Destructing Circle" << endl;
    }
};

// forkclass: 矩形
class Rectangle : public Shape {
private:
    double width;
    double height;
public:
    // constructfunction
    Rectangle(double w, double h) {
        width = w;
        height = h;
    }
    
    // implementation纯虚function
    void draw() override {
        cout << "Drawing a rectangle with width " << width << " and height " << height << endl;
    }
    
    double calculateArea() override {
        return width * height;
    }
    
    ~Rectangle() {
        cout << "Destructing Rectangle" << endl;
    }
};

// forkclass: 三角形
class Triangle : public Shape {
private:
    double a;
    double b;
    double c;
public:
    // constructfunction
    Triangle(double side1, double side2, double side3) {
        a = side1;
        b = side2;
        c = side3;
    }
    
    // implementation纯虚function
    void draw() override {
        cout << "Drawing a triangle with sides " << a << ", " << b << ", " << c << endl;
    }
    
    double calculateArea() override {
        // using海伦公式计算三角形面积
        double s = (a + b + c) / 2;
        return sqrt(s * (s - a) * (s - b) * (s - c));
    }
    
    ~Triangle() {
        cout << "Destructing Triangle" << endl;
    }
};

int main() {
    // creation基class指针array
    Shape* shapes[3];
    
    // 用forkclassobject初始化基class指针
    shapes[0] = new Circle(5.0);
    shapes[1] = new Rectangle(4.0, 6.0);
    shapes[2] = new Triangle(3.0, 4.0, 5.0);
    
    // polymorphism
    for (int i = 0; i < 3; i++) {
        shapes[i]->draw();
        cout << "Area: " << shapes[i]->calculateArea() << endl;
        cout << endl;
    }
    
    // 释放memory
    for (int i = 0; i < 3; i++) {
        delete shapes[i];
        cout << endl;
    }
    
    return 0;
}

互动练习

练习1: design一个动物class层次structure, includingabstraction基classAnimal and forkclassDog, Cat, Bird, implementationpolymorphism.

要求:

  • Animalclasspackage含纯虚functionmakeSound() and displayInfo()
  • Dogclass重写makeSound()method, 输出"Woof! Woof!"
  • Catclass重写makeSound()method, 输出"Meow! Meow!"
  • Birdclass重写makeSound()method, 输出"Tweet! Tweet!"
  • in 主functionin, creation不同动物 object, through基class指针调用虚function

练习2: design一个银行accountclass层次structure, including基classBankAccount and forkclassSavingsAccount, CheckingAccount.

要求:

  • BankAccountclasspackage含account余额, 存款 and 取款method
  • SavingsAccountclass添加利率property and 计算利息 method
  • CheckingAccountclass添加透支限额property, 允许account余额 for 负数但不超过透支限额
  • in 主functionin, creation不同class型 accountobject, test其functions

练习3: design一个员工class层次structure, including基classEmployee and forkclassFullTimeEmployee, PartTimeEmployee.

要求:

  • Employeeclasspackage含员工姓名, ID and 计算工资 虚function
  • FullTimeEmployeeclass添加月薪property
  • PartTimeEmployeeclass添加 small 时工资 and 工作 small 时数property
  • in 主functionin, creation不同class型 员工object, 计算并输出他们 工资