C++类的构造函数,什么时候需要程序员自己去写构造函数和析构函数

C++类默认会有构造函数和析构函数,然后我们用代码去实现一下,以及在什么情况下我们需要去重写构造函数和析构函数

默认的构造函数

1.无参构造

#include <iostream>
using namespace std;
class test{
public:
    test(){
        cout<<"test的无参构造已经被调用"<<endl;
    };
private:
    int m_i;
};
int main(){
    test temp=test();
}

运行结果如下

 

当我们删除他,即用delete操作符删除,编辑器就会给我们报错

 

2.默认拷贝构造函数

//
// Created by 18751 on 2023/5/20.
//
#include <iostream>
using namespace std;
class test{
public:
    test(){
        cout<<"test的无参构造已经被调用"<<endl;
    };
    test(const test &temp):m_i(temp.m_i){
        cout<<"test的拷贝构造已经被调用"<<endl;
    }
private:
    int m_i;
};
int main(){
    test temp;
    test temp2(temp);
}

至于为什么是引用传递呢,假如我们用值传递我们可能会有更大的空间开销。不如直接用引用传递节省空间。

3.赋值构造函数

赋值构造函数我们得要知道运算符的重载(是C++多态的一种),因为类不是基本数据类型。我们需要重载运算符才可以对类和类之间使用赋值运算符。
//
// Created by 18751 on 2023/5/20.
//
#include <iostream>
using namespace std;
class test{
public:
    test():m_i(0){
        cout<<"test的无参构造已经被调用"<<endl;
    };
    test(const test &temp):m_i(temp.m_i){
        cout<<"test的拷贝构造已经被调用"<<endl;
    }
    test& operator=(const test& other){
        if(this==&other){
            return *this;
        }
        m_i=other.m_i;
    }
private:
    int m_i;
};
int main(){
    test temp;
    test temp2(temp);
}

在什么时候我们需要自己去写构造函数和析构函数呢?

当我们的成员函数都在栈上的话,我们不需要考虑去重写构造方法。只有当我们的变量在堆上开辟的时候,我们需要重写构造函数和析构函数,防止两个对象的指针指向同一片内存空间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值