首先说明一下:拷贝构造函数和赋值函数还不一样
拷贝构造函数:刚刚开辟好一块内存空间,就是利用传入的对象对这块内存进行初始化(注意深拷贝和浅拷贝的问题)
拷贝构造::一种特殊的构造函数,用基于同一类的一个对象构造和初始化另一个对象。
当没有拷贝构造函数时,通过默认拷贝构造函数来创建一个对象。
A a;
A b(a);
A b= a;
都是拷贝构造函数来创建对象b
b 对象之前是不存在的,用a对象来构造和初始化b的!!!
何时调用拷贝构造函数
1. 对象以值传递的方式传入函数内
2. 对象以值传递的方式从函数返回
3. 对象需要通过另一个对象初始化
赋值函数:已经有一个已经初始化好的对象,说明此时已经调用过普通的构造函数,此时传入另一个对象对它进行赋值,需要先delete释放原来对象的内存空间,然后重新开辟空间使用传进来的对象进行赋值。
赋值函数:: 一个类的对象向该类的另一个对象赋值。
当没有重载赋值函数(赋值运算符)时,通过默认赋值函数来进行赋值操作。
A a;
A b;
b =a ;
a, b 对象是已经存在的,用a对象来赋值给b!!!!!!
赋值运算符的重载声明:
A& operator = (const A& other)
转载原文地址:
https://blog.youkuaiyun.com/caoshangpa/article/details/51530482
请编写String的上述4个函数。
这个在面试或笔试的时候常问到或考到。
已知类String的原型为:
-
class String
-
{
-
public:
-
String(const char *str = NULL);// 普通构造函数
-
String(const String &other);// 拷贝构造函数
-
~String(void);// 析构函数
-
String & operator = (const String &other);// 赋值函数
-
private:
-
char *m_data;// 用于保存字符串
-
};
请编写String的上述4个函数。
-
//普通构造函数
-
String::String(const char *str)
-
{
-
if (str == NULL)
-
{
-
m_data = new char[1];// 得分点:对空字符串自动申请存放结束标志'\0'的,加分点:对m_data加NULL判断
-
*m_data = '\0';
-
}
-
else
-
{
-
int length = strlen(str);
-
m_data = new char[length + 1];// 若能加 NULL 判断则更好
-
strcpy(m_data, str);
-
}
-
}
-
// String的析构函数
-
String::~String(void)
-
{
-
delete[] m_data; // 或delete m_data;
-
}
-
//拷贝构造函数
-
String::String(const String &other)// 得分点:输入参数为const型
-
{
-
int length = strlen(other.m_data);
-
m_data = new char[length + 1];// 若能加 NULL 判断则更好
-
strcpy(m_data, other.m_data);
-
}
-
//赋值函数
-
String & String::operator = (const String &other) // 得分点:输入参数为const型
-
{
-
if (this == &other)//得分点:检查自赋值
-
return *this;
-
if (m_data)
-
delete[] m_data;//得分点:释放原有的内存资源
-
int length = strlen(other.m_data);
-
m_data = new char[length + 1];//加分点:对m_data加NULL判断
-
strcpy(m_data, other.m_data);
-
return *this;//得分点:返回本对象的引用
-
}