C++中构造函数,拷贝构造函数和赋值操作符的使用

1.我们知道在创建一个对象的时候 ,这3个函数都可以用来对一个对象进行初始化,那么这3个函数调用的时间分别是在什么时候呢。写一个函数验证一下:

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

class MyString
{
private:
    char *m_data;
    int data;
public:
    //普通构造函数
    MyString(const char * str  = NULL,const int s = 0);
    //拷贝构造函数
    MyString(const MyString & other);
    //重载操作符号
    MyString& operator = (const MyString& my);
    //析构函数
    ~MyString();
    //赋值函数
    //MyString & operator = (const MyString &other);


};


MyString::MyString(const char *str,const int s)
{
    data = s;
    cout << "constructing  string by " << str << endl;
    if(str == NULL)
    {
        m_data = new char[1];
        *m_data = '\0';

    }
    else
    {
        int len = strlen(str);
        m_data = new char[len + 1];
        strcpy(m_data,str);
    }
}

MyString::MyString(const MyString & other)
{
    cout << "constructing by other MyString " << other.m_data << endl;
    int length = strlen(other.m_data);
    m_data = new char[length + 1];
    strcpy(m_data,other.m_data);
}

MyString& MyString::operator= (const MyString& my)
{
    cout << "constructing by operator = " << endl;
    int length = strlen(my.m_data);
    m_data = new char[length + 1];
    strcpy(m_data,my.m_data);
    return *this;
}

MyString::~MyString()
{
    cout <<"destructing \n" ;
    delete m_data;
}
int main()
{
    MyString s1("hehe");
    MyString s = s1;
    s = s1;
    MyString s2 = s1;
    s2 = s1;
    //MyString s3;
    return 0;
}

我们在这个函数中分别定义了构造函数,拷贝构造函数和赋值操作符,打印一下输出结果,看下都是什么时候调用的。


代码:

MyString s1("hehe");   //这个是调用的构造函数   MyString(const char * str  = NULL,const int s = 0);
    MyString s = s1;   //这个调用的是赋值(拷贝)构造函数  MyString(const MyString & other);
    s = s1;           //这个调用的是重载操作符  MyString& operator = (const MyString& my);
    MyString s2 = s1; //这个调用的是赋值(拷贝)构造函数  MyString(const MyString & other);

    s2 = s1;//这个调用的是重载操作符  MyString& operator = (const MyString& my);



可以得出结论:

用一个已存在的对象去构造一个不存在的对象(构造之前不存在),就是拷贝构造.
用一个已存在的对象去覆盖另一个已存在的对象,就是赋值运算.


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值