首页 > 其他 > 详细

struct 和 class的区别

时间:2021-02-12 08:16:48      阅读:55      评论:0      收藏:0      [点我收藏+]

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

struct 和 class的区别

原文:https://www.cnblogs.com/tan-wm/p/14398220.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!