正文

重新认识struct(1)2005-08-15 11:40:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/edwardguo/3816.html

分享到:

建议结合使用《the c programming language》来阅读本文,相关书籍在网上均有电子版.

在描述struct前,我们先来了解一下what is a type?
A type is a concrete representation of a concept.
For example,the c++ built-in type float with its operations +,-,*,etc.,provides a concrete approximation of the mathematical concept of a real number. (摘于《the c++ programming language》chapter 10)
由此,我们可以明确的知道,a type is a concept.这个type包含的不仅仅是一个像int,double这样的一个符号,更多的是在表示一种concept。一个类型的内涵,还包括其运算方式,其使用范围,其用法等等一系列的问题。

现在进行分析,struct是什么:
A structure is a collection of one or more variables, possibly of different types.(K&R 《the c programming language》)
由此可以明确的是,struct组合的是一组concept并把它表示为一个concept.由于这种组合的特殊性,虽然方便但在作为一个整体使用,必然要在一定程度上限定其应用.所以有下:
structures may be copied and assigned to, passed to functions,and returned by functions.(K&R 《the c programming language》)
描述struct的使用方式。
以上具体的描述了struct,为之后理解struct有很重要的意义。

struct实际应用的意义:
通常情况下,我们会用一个struct来定义一个树,定义一个线形表,而不会使用一个类来表示,因为,类是具体对象的抽象,也就是说,我们描述的树和线形表还不够具体到需要用类来描述,其不具体到不需要描述其行为(成员函数)的程度,因此,struct为我们提供了一个很好的描述机制,它组合了一组数据,而又不需要来描述足够具体了实体。


struct基础说明:
1.The keyword struct introduces a structure declaration, which is a list of declarations enclosed in braces. An optional name called a structure tag may follow the word struct.The variables named in a structure are called members.(K&R 《the c programming language》)
例如:
struct point{
    int x;
    int y;
};
这里point就是structure tag.x,y 就是member.
熟悉各个概念是为了更好的继续阅读以后的文章.
这里还可以谈及一个有关命名的问题,member的名称可以于外部变量相同,因为我们总是可以通过上下文进行区分(they can always be distinguished by context.)更明确的说法是,我们都可以通过变量来区别他们应用的成员.其实,这里设计到的是一个有关块结构的问题,有关块结构的作用域的问题可以参考<<C++ how to program>>chapter 3(H.M.Deitel,P.J.Deitel著)
附加语法知识:在定义任何自定义类型及其初始化时后面都要在大括号后面加一个";"表示结束.其他情况的大括号后面均无需加";".关于内部类型和自定义类型的概念参见<<the c++ programming language>>.

2.A structure declaration that is not followed by a list of variables reserves no storage; it merely describes a template or shape of a structure.(K&R 《the c programming language》)
也就是说,结构的申明只是在描述一种模板,而不占据空间.

3.初始化问题:
A structure can be initialized by following its definition with a list of initializers, each a constant expression, for the
members:
struct point maxpt = { 320, 200 };  //注意只有在定义的同时可以使用这样的赋值形式.
任何类型都可以在定义的时候初始化,并且都是用赋值符号来实现.
假如没有在定义时候初始化,就需要用 varialbe.member(书中是structure-name.member,笔者觉得用variable描述更加妥当)

4.Structures can be nested.
支持嵌套.
eg.:
struct point{
    int x;
    int y;
};
struct rect{
    struct point p1;
    struct point p2;
};

阅读(3759) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册