在 C++ 中,陣列成員是深度複製的嗎?
在 C/C++ 中,我們可以將一個結構(或僅限 C++ 中的類)變數賦值給另一個同類型變數。在將一個結構變數賦值給另一個變數時,該變數的所有成員都會複製到另一個結構變數。在此情況下,會產生一個問題,即當結構包含一個數組時會發生什麼?
現在,我們來討論陣列。需要注意的主要一點是陣列成員不會作為淺複製複製;在陣列成員的情況下,編譯器會自動執行深度複製。在下面的程式中,結構體 test 包含陣列成員 str1[]。當我們能夠將 st1 賦值給 st2 時,st2 會獲得陣列的一個新副本。因此,當我們修改或更改 st1 中的 str[] 時,st2 不會被修改或更改。
示例
# include <iostream>
# include <string.h>
using namespace std;
struct test{
char str1[20];
};
int main(){
struct test st1, st2;
strcpy(st1.str1, "Tutorial Point");
st2 = st1;
st1.str1[0] = 'X';
st1.str1[1] = 'Y';
/* Because copy was Deep, both arrays are different */
cout<< "st1's str = " << st1.str1 << endl;
cout<< "st2's str = " << st2.str1 << endl;
return 0;
}輸出
st1's str = XYtorial Point st2's str = Tutorial Point
因此,在 C++ 類中,我們不需要為陣列成員編寫自己的複製建構函式和賦值運算子,因為預設行為對於陣列來說是深度複製。
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP