Bootstrap

13x1类和对象-1

13x2类和对象-2

关注泷羽Sec-静安 公众号,后台回复 找书+ C++Primer 获取C++相关电子书

image-20250211221401317

  • 类:类是一个抽象的模板,用于定义对象的属性和行为。
  • 对象:对象是类的具体实例,通过类创建。

面向对象三大特性:

  • 封装 (Encapsulation):通过将数据成员设为私有(private),并提供公共(public)方法来控制对数据的访问,保护数据不被外部直接修改。
  • 继承 (Inheritance):通过继承基类的属性和方法,派生类可以复用基类的代码,并可以添加新的属性和方法。
  • 多态 (Polymorphism):通过基类指针或引用调用派生类的重写方法,实现同一接口的不同实现。
#include <iostream>
#include <string>

using namespace std;

/*----------- 类和对象基础 -----------*/
// 类:抽象模板 | 对象:具体实例
class Dog {          // 类声明
public:
    string name;     // 属性
    void bark() {    // 方法
        cout << name << ": Wang Wang!" << endl;
    }
};

// 使用示例:
int main() {
    Dog myDog;           // 创建对象
    myDog.name = "Buddy";
    myDog.bark();        // 输出:Buddy: Wang Wang!

    /*----------- 封装 (Encapsulation) -----------*/
    class BankAccount {
    private:             // 封装敏感数据
        double balance;

    public:
        // 公开接口控制访问
        void deposit(double amount) {
            if (amount > 0) balance += amount;
        }

        bool withdraw(double amount) {
            if (amount <= balance) {
                balance -= amount;
                return true;
            }
            return false;
        }

        double getBalance() { return balance; } // 只读访问
    };

    // 使用示例:
    BankAccount acc;
    acc.deposit(1000);      // 合法操作
    // acc.balance = 10000; // 错误:无法直接访问private成员

    /*----------- 继承 (Inheritance) -----------*/
    // 基类
    class Vehicle {
    public:
        string brand;
        void honk() {
            cout << "Tu~ Tu~" << endl;
        }
    };

    // 派生类
    class Car : public Vehicle { // 继承语法
    public:
        int wheels = 4;         // 新增属性
        void showSpec() {       // 新增方法
            cout << brand << " Car with " << wheels << " wheels" << endl;
        }
    };

    // 使用示例:
    Car myCar;
    myCar.brand = "BMW";  // 继承自基类
    myCar.honk();         // 调用基类方法
    myCar.showSpec();     // 输出:BMW Car with 4 wheels

    /*----------- 多态 (Polymorphism) -----------*/
    class Shape {  //一个形状
    public:
        virtual double area() { // 虚函数实现多态基础
            return 0;
        }
    };

    class Circle : public Shape { //圆
        double radius;
    public:
        Circle(double r) : radius(r) {}
        double area() override { // 重写基类方法
            return 3.14159 * radius * radius;
        }
    };

    class Rectangle : public Shape {  //角度
        double width, height;
    public:
        Rectangle(double w, double h) : width(w), height(h) {}
        double area() override { // 重写基类方法
            return width * height;
        }
    };

    // 使用示例:
    Shape* shapes[2];          // 基类指针数组
    shapes[0] = new Circle(5); // 指向派生类对象
    shapes[1] = new Rectangle(4, 6);

    // 同一接口表现不同行为
    cout << "Circle area: " << shapes[0]->area() << endl;  // 输出78.5397
    cout << "Rectangle area: " << shapes[1]->area() << endl; // 输出24

    /* 多态实现关键点:
    1. 基类方法声明为virtual
    2. 派生类使用override重写方法
    3. 通过基类指针/引用调用方法 */

    // 清理动态分配的内存
    delete shapes[0];
    delete shapes[1];

    return 0;
}
---
Buddy: Wang Wang!
Tu~ Tu~
BMW Car with 4 wheels
Circle area: 78.5397
Rectangle area: 24

三种访问权限

  • 公共权限(public):公共成员可以在任何地方访问,包括类外部和派生类中。
    示例:int publicVar; 可以在 main 函数中直接访问。
  • 保护权限(protected):保护成员只能在本类和派生类中访问,不能在类外部访问。
    示例:int protectedVar; 可以在派生类 Derived 中访问,但不能在 main 函数中直接访问。
  • 私有权限(private):私有成员只能在本类中访问,不能在类外部和派生类中访问。
    示例:int privateVar; 只能在 Base 类的成员函数中访问,不能在 main 函数和派生类 Derived 中直接访问。
#include <iostream>
#include <string>

using namespace std;

/*----------- 访问权限示例 -----------*/
class Base {
public:
    int publicVar; // 公共权限:任何地方都可以访问

protected:
    int protectedVar; // 保护权限:派生类和本类可以访问

private:
    int privateVar; // 私有权限:只有本类可以访问

public:
    // 构造函数
    Base(int pub, int prot, int priv) : publicVar(pub), protectedVar(prot), privateVar(priv) {}

    // 公共方法,访问私有成员
    void showPrivateVar() {
        cout << "Private Variable: " << privateVar << endl;
    }
};

// 派生类
class Derived : public Base {
public:
    // 构造函数
    Derived(int pub, int prot, int priv) : Base(pub, prot, priv) {}

    // 访问基类的保护成员
    void showProtectedVar() {
        cout << "Protected Variable: " << protectedVar << endl;
    }
};

int main() {
    // 创建基类对象
    Base baseObj(1, 2, 3);

    // 访问公共成员
    cout << "Public Variable: " << baseObj.publicVar << endl;

    // 访问私有成员(错误)
    // cout << "Private Variable: " << baseObj.privateVar << endl; // 错误:无法访问私有成员

    // 通过公共方法访问私有成员
    baseObj.showPrivateVar();

    // 创建派生类对象
    Derived derivedObj(4, 5, 6);

    // 访问基类的公共成员
    cout << "Public Variable (Derived): " << derivedObj.publicVar << endl;

    // 访问基类的保护成员(错误)
    // cout << "Protected Variable (Derived): " << derivedObj.protectedVar << endl; // 错误:无法直接访问保护成员

    // 通过派生类方法访问基类的保护成员
    derivedObj.showProtectedVar();

    return 0;
}
---
Public Variable: 1
Private Variable: 3
Public Variable (Derived): 4
Protected Variable: 5

struct 和 class的区别

在C++中,struct 和 class 的主要区别在于默认的访问控制权限。以下是详细的解释和示例代码:
区别

  1. 默认访问控制权限:
    struct 的成员默认是 public。
    class 的成员默认是 private。
  2. 继承:
    struct 默认的继承方式是 public。
    class 默认的继承方式是 private。
#include <iostream>
#include <string>

using namespace std;

// 使用 struct
struct MyStruct {
    int publicVar; // 默认是 public

    MyStruct(int val) : publicVar(val) {}
};

// 使用 class
class MyClass {
    int privateVar; // 默认是 private

public:
    MyClass(int val) : privateVar(val) {}

    int getPrivateVar() const {
        return privateVar;
    }
};

int main() {
    // 使用 struct
    MyStruct s(10);
    cout << "MyStruct publicVar: " << s.publicVar << endl; // 可以直接访问

    // 使用 class
    MyClass c(20);
    // cout << "MyClass privateVar: " << c.privateVar << endl; // 错误:无法直接访问 private 成员
    cout << "MyClass privateVar: " << c.getPrivateVar() << endl; // 通过公共方法访问

    return 0;
}

---
MyStruct publicVar: 10
MyClass privateVar: 20

🔔 想要获取更多网络安全与编程技术干货?

关注 泷羽Sec-静安 公众号,与你一起探索前沿技术,分享实用的学习资源与工具。我们专注于深入分析,拒绝浮躁,只做最实用的技术分享!💻

扫描下方二维码,马上加入我们,共同成长!🌟

👉 长按或扫描二维码关注公众号

或者直接回复文章中的关键词,获取更多技术资料与书单推荐!📚

;