一篇文章让你学会构造函数和析构函数

构造函数

什么是构造函数?

定义:为对象进行初始化的函数。

作用:在创建对象时为对象成员属性赋值,构造函数由编译器自动调用,无需手动调用。

分类:按有无参数分为有参构造函数和无参构造函数;按类型分类分为普通构造和拷贝构造函数。        

#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;
}

运行的效果图如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值