1. 程式人生 > >C++語法,複製建構函式與=運算子過載

C++語法,複製建構函式與=運算子過載

複製程式碼
1、物件在建立時使用其他的物件初始化

Person p(q); //此時複製建構函式被用來建立例項p

Person p = q; //此時複製建構函式被用來在定義例項p時初始化p

2、物件作為函式的引數進行值傳遞時

f(p); //此時p作為函式的引數進行值傳遞,p入棧時會呼叫複製建構函式建立一個區域性物件,與函式內的區域性變數具有相同的作用域

需要注意的是,賦值並不會呼叫複製建構函式,賦值只是賦值運算子(過載)在起作用

p = q; //此時沒有複製建構函式的呼叫!

簡單來記的話就是,如果物件在宣告的同時將另一個已存在的物件賦給它,就會呼叫複製建構函式;如果物件已經存在,然後將另一個已存在的物件賦給它,呼叫的就是賦值運算子(過載)

預設的複製建構函式和賦值運算子進行的都是
"shallow copy",只是簡單地複製欄位,因此如果物件中含有動態分配的記憶體,就需要我們自己重寫複製建構函式或者過載賦值運算子來實現"deep copy",確保資料的完整性和安全性。
複製程式碼

eg:

string.h

複製程式碼
#include<iostream>
#include<cstring>
#ifndef STRING_H_
#define STRING_H_
class string
{
private:
    char *data;
public:
    string();
    string(const char *value);
    string
(const string & s); ~string(); operator=(const string & s); }; #endif
複製程式碼

string_h.cpp

複製程式碼
#include"string.h"
using std::cout;
using std::endl;

string::string()
{
    data=new char[4];
    data="c++";
   cout<<"建構函式無參:"<<data<<endl;

}

string::string(const char *value)
{
    
if(value) { data=new char[strlen(value)+1]; strcpy(data,value); } else { data=new char[1]; *data='\0'; } cout<<"建構函式有參:"<<data<<endl; } string::string(const string & s) { data=new char[strlen(s.data)+1]; strcpy(data,s.data); cout<<"複製建構函式:"<<data<<endl; } string::~string() { delete [] data; } string::operator =(const string & s) { data=new char[strlen(s.data)+1]; strcpy(data,s.data); cout<<"過載操作符=:"<<data<<endl; }
複製程式碼

string.cpp

複製程式碼
#include<iostream>
#include"string.h"

int main()
{
    string a("hello"); // 定義並構造 a ,有參構造
    string b(a); // 定義並構造b,顯式呼叫複製建構函式
    string c;//無參構造 
    c=a;//呼叫操作符過載
    string d=c;//隱式呼叫複製建構函式,而不是操作符過載
    return 0;
}
複製程式碼