关于C_C++中struct与class的区别

来源:互联网 发布:李涛疯狂淘宝 编辑:程序博客网 时间:2024/06/06 05:18

      我们经常回头想想,在学习完C语言后再去学C++时候可能经常不会想起当时会不会比较C中struct

和C++中的class的区别,或许有时候会。如果你看了《C++ Primer》第四版(P66),他里面是这

样介绍:

Using the struct Keyword

   If we define a class using the class keyword ,then any define before the first access label are implicitly private;if we use struct keyword ,then those members are public. Whether we define a class using the keyword class or the struct keyword affects only the default initial access level.
然后下面的Note:

The only difference between a class defined with the class keyword or the struct keyword
 is the default access level:By default,member in a struct are public;those in a class are private.

  总结上面的意思:

用结构体struct时候,它默认的变量的访问属性都是public的;而类(class)中的默认的变量访问都是隐含式的私有(implicitly private),这是关键字struct和关键字class的唯一区别(The only difference)!


如上面所说的,关键字struct中变量访问权限默认的是public,只是默认的!所以你可以改:
class student {       public:            void setName();            void getName();                 ...        //作为例子就不扯很多       private:            string stuName;}

可以改成:
typedef struct stdudent{     viod setName();     viod getName();      //请看下面:     private:         std::string stuName;}//看上去很想class啊!
       这下好了!初学者都会犯迷糊了(包括自己):到底用struct还是class呢?上面写的时候,包括Stanley B.Lippman

都每次写struct和class时候前面加上“关键字”(keyword),可以这么理解;他们单独来讲的时候,撇开实际上下文用法,他们的区别只是

语义上的。所谓语义上的的差别,就是说在语言里面,桌子和米饭两个名词只是意义不同,如果不放进具体语言中去(即上下无关文法,

文法即语法),没有任何差别。如:吃米饭、吃桌子,就是语义上的不同!也就是说吃桌子也是成立的!听起来挺玄乎的?!

      上面是从局部说两者的差别。但实际来讲,这是两种不同的程序设计思想啊!!!一种是结构式设计,另一种是面向对象设计!这也是

两者的一个区别!并且是本质的区别。class封装的对象可以有很多不一样的用处;而struct可以说只是一种特殊的自定义类型!本质似乎和

int、string、char类型是一样的。你可以这样:

typedef struct student ;student stu_1;student stu_2;         .         .         .student stu_n;
看上去和下面的很像:

char student[1];char student[2]; . . .char student[n];
     当然,上面写的并不是想迷惑你,只是想更好的理解。至于其他的区别,只是使用上的了。当然了,其实还是设计思想上的本质区别!

     希望有点帮助。








原创粉丝点击