构造函数
什么是构造函数?
定义:为对象进行初始化的函数。
作用:在创建对象时为对象成员属性赋值,构造函数由编译器自动调用,无需手动调用。
分类:按有无参数分为有参构造函数和无参构造函数;按类型分类分为普通构造和拷贝构造函数。
#include <iostream>
#include <string>
class Car {
private:
std::string make;
std::string model;
int year;
public:
// 构造函数用于初始化对象
Car(std::string make, std::string model, int year) {
this->make = make;
this->model = model;
this->year = year;
}
void displayInfo() {
std::cout << "Car Info: " << year << " " << make << " " << model << std::endl;
}
};
int main() {
// 没有使用构造函数进行初始化
Car car1;
car1.displayInfo(); // 编译错误:没有匹配的构造函数
// 使用构造函数进行初始化
Car car2("Toyota", "Camry", 2020);
car2.displayInfo(); // 输出:Car Info: 2020 Toyota Camry
return 0;
}
运行的错误说明没有调用到构造函数,没有进行初始化。
如何进行初始化呢?对构造函数的成员变量进行赋值。
介绍一些有参构造函数和无参构造函数,拷贝函数
#include <iostream>
#include <string>
using namespace std;
class Car
{
public:
Car()
{
cout<<"无参构造函数的调用"<<endl;
};
Car(string s )
{
cout<<"有参构造函数的调用"<<endl;
}
Car (const Car &p)
{
cout<<"拷贝函数的调用"<<endl;
}
};
int main() {
Car car;
Car car1("1");
Car car2(car1);
return 0;
}
你可能会问拷贝函数为什么要加const来声明呢?
因为调用拷贝函数是为了创建一个新对象,同时它也拷贝了其他函数的属性和功能,为了让拷贝过来的属性不受其他函数(拷贝函数中属性的原函数)影响,所以添加const关键字,这样拷贝函数中的属性就不会被轻易修改了。
析构函数
什么是析构函数?
定义:对调用完的对象进行清理的函数。
作用:在对象销毁前系统自动调用析构函数,执行一些清理工作;析构函数由编译器自动调用,无需手动调用。
#include <iostream>
#include <string>
using namespace std;
class Car {
private:
std::string make;
std::string model;
int year;
public:
// 构造函数用于初始化对象
Car(std::string make, std::string model, int year) {
this->make = make;
this->model = model;
this->year = year;
}
~Car()
{cout<<"调用析构函数"<<endl;};
void displayInfo() {
std::cout << "Car Info: " << year << " " << make << " " << model << std::endl;
}
};
int main() {
// 没有使用构造函数进行初始化
//Car car1;
//car1.displayInfo(); // 编译错误:没有匹配的构造函数
// 使用构造函数进行初始化
Car car2("Toyota", "Camry", 2020);
car2.displayInfo(); // 输出:Car Info: 2020 Toyota Camry
return 0;
}
运行的效果图如下