struct 和 class的区别

struct默认成员为public的,class默认成员为private的,此外并没有什么区别

所以用一个结构体给另一个结构体赋值时,一般结构体里如果没有定义赋值运算符,则会像类那样使用默认赋值运算符或默认拷贝构造函数。

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 struct xiaomao
 6 {
 7     int a;
 8     float b;
 9     int c[3];
10 };
11 
12 struct damao
13 {
14     int a;
15     float b;
16     int *c;
17 };
18 
19 
20 int main()
21 {
22     xiaomao aa = {1,2.0,{3,4,5}};
23     cout << "aa" << endl;
24     cout << aa.a << endl;
25     cout << aa.b << endl;
26     cout << aa.c[0] << " " << aa.c[1] << " " << aa.c[2] << endl;
27     xiaomao bb = aa;
28     cout << "bb" << endl;
29     cout << bb.a << endl;
30     cout << bb.b << endl;
31     cout << bb.c[0] << " " << bb.c[1] << " " << bb.c[2] << endl;
32     bb.c[0] = 666;
33     cout << "after change: bb.c[0]:" << bb.c[0] << "  " << "aa.c[0]:" << aa.c[0] << endl;
34     damao cc;
35     cc.a = 12;
36     cc.b = 13.0;
37     cc.c = new int[2];
38     cc.c[0] = 5;
39     cc.c[1] = 6;
40     cout << "cc" << endl;
41     cout << cc.a << endl;
42     cout << cc.b << endl;
43     cout << cc.c[0] << " " << cc.c[1]  << endl;
44     damao dd = cc;
45     cout << "dd" << endl;
46     cout << dd.a << endl;
47     cout << dd.b << endl;
48     cout << dd.c[0] << " " << dd.c[1]  << endl;
49 
50     dd.c[0] = 666;
51     cout << "after change: dd.c[0]:" << dd.c[0] << "  " << "cc.c[0]:" << cc.c[0] << endl;
52 
53     return 0;
54 }

 

运行结果:

aa
1
2
3 4 5
bb
1
2
3 4 5
after change: bb.c[0]:666  aa.c[0]:3
cc
12
13
5 6
dd
12
13
5 6
after change: dd.c[0]:666  cc.c[0]:666

上一篇:为什么 Python 的 f-string 可以连接字符串与数字?


下一篇:数据的输入和输出