关键字 this

this的使用案例

#include <iostream>
#include <string>
using namespace std; // 使用std命名空间
class Car {
public:
    string brand; // 不需要使用std::string
    int year;
    // 有参函数
    Car(string brand,int year) {
        this->brand = brand;
        this->year  = year;
        cout << "有参构造函数被调用" << endl; // 不需要使用std::cout和std::endl
    }
    void display() const {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
    Car& Setyear(int year){
        this->year = year;
        return *this;
    }
};
int main() {
    Car myCar("宾利",2021); // 创建Car对象
    myCar.display(); // 显示车辆信息

    myCar.Setyear(2024).display();
    return 0;
}

 new

为指针型的变量 开辟空间

Car* pcar = new Car("奥迪",2009);

1分配单个对象:

使用 new 可以在堆上动态分配一个对象。例如, new int 会分配一个 int 类型的空 间,并返回一个指向该空间的指针。 

int* ptr = new int; //C语言中,int *p = (int *)malloc(sizeof(int));

 2分配对象数组

: new 也可以用来分配一个对象数组。例如, new int[10] 会分配一个包含10个整数的 数组。

int& arr = new int[10];
int* arr = new int[10]; //C语言中,int *arr = (int *)malloc(sizeof(int)*10);

 3初始化:

可以在 new 表达式中使用初始化。对于单个对象,可以使用构造函数的参数:

MyClass* obj = new MyClass(arg1, arg2);
Car* obj = new Car(arg1,arg2);

delete

释放申请的指针型空间。

释放单个

delete str;

释放数组

delete[] arr; // 释放 arr 指向的数组

例子

class MyClass {
public:
    MyClass() {
        std::cout << "Object created" << std::endl;
}
};
int main() {
    // 分配单个对象
    MyClass* myObject = new MyClass();
    // 分配对象数组
    int* myArray = new int[5]{1, 2, 3, 4, 5};
    // 使用对象和数组...
    // 释放内存
    delete myObject;
    delete[] myArray;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值