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);
可以得出结论:
用一个已存在的对象去构造一个不存在的对象(构造之前不存在),就是拷贝构造.
用一个已存在的对象去覆盖另一个已存在的对象,就是赋值运算.