关键字 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;
}