C++中struct也有构造函数与析构函数,也可以有访问类型控制以及结构体大小,类大小

C++中struct也有构造函数与析构函数,也可以有访问类型控制,可以用private关键字。如下所示:

[cpp]  view plain  copy
  1. #include <iostream>    
  2.   
  3. struct point    
  4. {    
  5. public:    
  6.     point():x_(0.0),y_(0.0)    
  7.     {    
  8.         std::cout<<"default constructor point\n";          
  9.     }       
  10.     point(double x,double y):x_(x),y_(y)    
  11.     {    
  12.         std::cout<<"constructor point("<<x<<", "<<y<<")\n";    
  13.     }    
  14.     ~point()    
  15.     {    
  16.         std::cout<<"default destructor point\n";    
  17.     }    
  18.         
  19.     double get_x()    
  20.     {    
  21.         return x_;    
  22.     }    
  23.         
  24.     double get_y()    
  25.     {    
  26.         return y_;      
  27.     }    
  28.         
  29. private:    
  30.     double x_;    
  31.     double y_;    
  32. };    
  33.   
  34. class point_class  
  35. {    
  36. public:    
  37.     point_class():x_(0.0),y_(0.0)    
  38.     {    
  39.         std::cout<<"default constructor point_class\n";          
  40.     }       
  41.     point_class(double x,double y):x_(x),y_(y)    
  42.     {    
  43.         std::cout<<"constructor point_class("<<x<<", "<<y<<")\n";    
  44.     }    
  45.     ~point_class()    
  46.     {    
  47.         std::cout<<"default destructor point_class\n";    
  48.     }    
  49.         
  50.     double get_x()    
  51.     {    
  52.         return x_;    
  53.     }    
  54.         
  55.     double get_y()    
  56.     {    
  57.         return y_;      
  58.     }    
  59.         
  60. private:    
  61.     double x_;    
  62.     double y_;    
  63. };    
  64.   
  65.   
  66. int main()    
  67. {    
  68.     point pt;   
  69.     std::cout << pt.get_x() << "\n";  
  70.     std::cout << pt.get_y() << "\n";  
  71.     std::cout << "sizeof( double ): " << sizeofdouble ) <<   
  72.         ", sizefof( point ): " << sizeof( point ) << "\n";  
  73.   
  74.     point_class pt_c;  
  75.     std::cout << "sizeof( double ): " << sizeofdouble ) <<   
  76.         ", sizefof( point_class ): " << sizeof( point_class ) << "\n";  
  77. }  


输出结果为:

default constructor point
0
0
sizeof( double ): 8, sizefof( point ): 16
default constructor point_class
sizeof( double ): 8, sizefof( point_class ): 16
default destructor point_class
default destructor point

看来,struct与class是小异大同。struct默认访问权限是public,class是private;class有继承,多态机制,而struct没有。

C语言的区别:

1、C++中struct可以定义函数,但是C语言中struct只可以定义函数指针。

2、C语言中sizeof( struct ),会把定义的函数指针计算大小;C++中sizeof( struct ) 和 sizeof( class )都不会计算函数的大小,只会计算成员变量的大小。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值