c++构造函数和析构函数详解

有参构造函数

#include <iostream>
#include <cstdlib>
using  namespace std;
class  student {
    int age;
    int goal;
    char *name;
public:
    student(char *inputname) {
        name = new char[10];//**can not use the name=inputname;**
        strcpy(name, inputname);

    }

    void show() {
        cout << name;
    }
};
int main() {
    student a("test");
    a.show();
    return 0;
}

因为name指是指向内存堆区的,如果使用name=input_name;会造成指针指向改变不是指向堆区而是指向栈区,导致在后面调用析构函数delete释放堆空间出错!(析构函数的内容我们后面将要介绍)
如果需要调用能够执行就需要再添加一个没有参数的构造函数

#include <iostream>
using namespace std;

class MyClass
{
public:
    MyClass()
    {
        cout << "Constructors" << endl;
    }

    ~MyClass()
    {
        cout << "Destructors" << endl;
    }
};

int main()
{
    MyClass* pMyClass =  new MyClass;
    pMyClass->~MyClass();
    delete pMyClass;

    return 0;
}

结果为:
Constructors
Destructors//显示调用的析构函数
Destructors//delete调用的析构函数
拷贝构造函数

#include <iostream>  
using namespace std;  
  
class CExample {  
private:  
     int a;  
public:  
      //构造函数  
     CExample(int b)  
     { a = b;}  
  
      //一般函数  
     void Show ()  
     {  
        cout<<a<<endl;  
      }  
};  
  
int main()  
{  
     CExample A(100);  
     CExample B = A; //注意这里的对象初始化要调用拷贝构造函数,而非赋值  
      B.Show ();  
     return 0;  
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值