主要理解一下两点:

1.在C和C++中struct的常规使用。

2.在C++中struct和class基本一致,除了在访问控制权限方面,即:

    通过struct关键字实现的类,属性,函数默认的访问权限为public;
    通过class关键字实现的类,属性,函数默认的访问权限为private。

下面举例说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include<iostream>
using namespace std;
 
struct point{
    int x;
    int y;
    int fun(point &p)       //在C++中,完全可以在struct中使用函数
    {
        p.x = 100;
        p.y = 200;
        return 0;
    }
    point(int x, int y): x(x) , y(y){ }     //等同于C++中的class
};
struct teacher{
    int age;
    char *name;
};
int main(void){
    point p(0,0);
    p.x = 1;
    p.y = 2;
    point p1= p;
    cout<<"p1.x="<<p1.x<<endl;
    cout<<"p1.y="<<p1.y<<endl;
 
    point *p3 = &p1;
    p3->x = 10;
    p3->y = 20;
    cout<<"p3->x="<<p3->x<<endl;
    cout<<"p3->y="<<p3->y<<endl;
 
    p3->fun(p1);
    cout<<"p3->x="<<p3->x<<endl;
    cout<<"p3->y="<<p3->y<<endl;
 
    point p4(1000,2000);
    cout<<"p4.x="<<p4.x<<endl;
    cout<<"p4.y="<<p4.y<<endl;
 
    cout<<"================struct在C中用法================"<<endl;
    cout<<"before define struct teacher,sizeof(teacher)="<<sizeof(teacher)<<endl;
 
    struct teacher t1;              //定义时比较繁琐,需要添加struct关键字,也可以使用typedef声明,此处就不需要加struct关键字。同样在C++中可以直接不加struct关键字
 
    cout<<"after define struct teacher,sizeof(teacher)="<<sizeof(teacher)<<endl;
 
    t1.age = 30;
    t1.name = "zhangsan";
    cout<<"t1.age="<<t1.age<<endl;
    cout<<"t1.name="<<t1.name<<endl;
 
    struct teacher *t2 = &t1;
    t2->age = 35;
    t2->name = "lisi";
    cout<<"t2->age="<<t2->age<<endl;
    cout<<"t2->name="<<t2->name<<endl;
 
    system("pause");
    return 0;
}

  输出结果:

 

posted on   我得去图书馆了  阅读(5859)  评论(0编辑  收藏  举报
努力加载评论中...

点击右上角即可分享
微信分享提示