一说 拷贝构造函数 && 拷贝赋值函数
特别说明:
拷贝构造函数和拷贝赋值函数要成对出现
移动构造函数和移动赋值函数也要成对出现
拷贝构造函数是在对象被创建时调用的,而赋值函数只能在已经存在了的对象调用。看下面代码:
String a("hello");
String b("world");
String c = a;//这里c对象被创建调用的是拷贝构造函数
//一般是写成 c(a);这里是与后面比较
c = b;//前面c对象已经创建,所以这里是赋值函数
上面说明出现“=”的地方未必调用的都是赋值函数(算术符重载函数),也有可能拷贝构造函数,那么什么时候是调用拷贝构造函数,什么时候是调用赋值函数你?判断的标准其实很简单:如果临时变量是第一次出现,那么调用的只能是拷贝构造函数,反之如果变量已经存在,那么调用的就是赋值函数。
示例代码:
string.h
#ifndef __MYSTRING__
#define __MYSTRING__
#include <string.h>
class String {
public:
String(const char* cstr = 0); // 构造函数
String(const String& str); // 拷贝构造函数 ==》 String s2(s1)
String& operator = (const String& str); // 拷贝赋值函数 ==》 String s2 = s1
~String();
char* get_c_str() const { return m_data;}
private:
char* m_data;
};
inline String::String(const char* cstr)
{
if (cstr) {
m_data = new char[strlen(cstr) + 1];
strcpy(m_data, cstr);
} else {
m_data = new char[1];
*m_data = '\0';
}
}
inline String::String(const String& str)
{
m_data = new char[strlen(str.m_data) + 1];
strcpy(m_data, str.m_data);
}
inline String& String::operator = (const String& str)
{
if (this == &str) { // 检测自我赋值
return *this;
}
delete[] m_data;
m_data = new char[strlen(str.m_data) + 1];
strcpy(m_data, str.m_data);
return *this;
}
inline String::~String()
{
delete[] m_data;
}
#endif
string.cpp
#include "string.h"
#include <iostream>
using namespace std;
ostream& operator << (ostream& os, const String& str)
{
os << str.get_c_str();
return os;
}
int main()
{
String s1;
String s2("hello");
String s3(s1);
cout << s3 << endl;
s3 = s2;
cout << s3 << endl;
}
output
PS C:\Users\localuser> cd "c:\Users\localuser\Desktop\" ; if ($?) { g++ string.cpp -o string} ; if ($?) { .\string}
hello
还没有评论,来说两句吧...