C語言結構體物件間直接賦值
阿新 • • 發佈:2019-01-06
C語言中變數間互相賦值很常見,例如:
int a,b;
a = b;
結構體也是變數(自定義變數),兩個結構體之間直接賦值按道理應該也是可以的吧,說實話之前還從沒遇到過將一個結構體物件賦值給另一個結構體物件的(見識太淺),那麼下面做一個測試看看:
#include "stdio.h"
struct test
{
int a;
int b;
int c;
char *d;
};
int main()
{
struct test t1 = {1,2,3,"tangquan"};
struct test t2 = {0,0,0,""};
printf ("%d,%d,%d,%s\r\n",t2.a,t2.b,t2.c,t2.d);
t2 = t1;
printf("%d,%d,%d,%s\r\n",t2.a,t2.b,t2.c,t2.d);
return 0;
}
執行結果是:
tq@ubuntu:/mnt/hgfs/vmshare$ gcc test.c -o tar
tq@ubuntu:/mnt/hgfs/vmshare$ ./tar
0,0,0,
1,2,3,tangquan
很顯然賦值之後t2結構體的內容全部賦值為了t1的內容,假設正確。那麼C++中的類之間的相互賦值應該也是可以的了?