c++ struct

以前没怎么关注过这个点,记录一下

http://blog.csdn.net/ucasliyang/article/details/52691619

在做一个小的程序题的时候,看到了struct中定义了函数,之前没有看到过,所以查了一点相关的知识,在这里记录一下:

c++中允许在结构体当中定义函数,它的用法和类的用法很像,不过与类有一个区别在于,struct中定义的函数和变量都是默认为public的,但class中的则是默认为private。

[cpp]  view plain  copy
  1. #include<iostream>  
  2. #include<string>  
  3.   
  4. struct Person  
  5. {  
  6.   Person(std::string name);  
  7.   std::string greet(std::string other_name);  
  8.   std::string m_name;  
  9. };  
  10.   
  11. Person::Person(std::string name)  
  12. {  
  13.     m_name = name;  
  14. }  
  15.   
  16. std::string Person::greet(std::string other_name)  
  17. {  
  18.     return "Hi " + other_name + ", my name is " + m_name;  
  19. }  
  20.   
  21. int main()  
  22. {  
  23.     Person m_person("JANE");  
  24.     std::string str = m_person.greet("JOE");  
  25.     std::cout<<str<<std::endl;  
  26. }  



http://blog.csdn.net/devil_2009/article/details/6871324

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

[cpp]  view plain  copy
 print ?
  1. <span style="font-size:16px;"><strong>#include<iostream>  
  2. #include<ostream>  
  3.  struct point  
  4.  {  
  5.     public:  
  6.     point():x_(0.0),y_(0.0)  
  7.     {  
  8.         std::cout<<"default constructor\n";        
  9.     }     
  10.     point(double x,double y):x_(x),y_(y)  
  11.     {  
  12.         std::cout<<"constructor("<<x<<", "<<y<<")\n";  
  13.     }  
  14.     ~point()  
  15.     {  
  16.         std::cout<<"default destructor\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.  int main()  
  34.  {  
  35.     point pt;  
  36.     std::cout<<pt.get_x()<<"\n";  
  37.     std::cout<<pt.get_y()<<"\n";   
  38.  } </strong></span>  
输出结果为:

[cpp]  view plain  copy
 print ?
  1. <strong>default constructor  
  2. 0  
  3. 0  
  4. default destructor</strong>  
看来真像某些人说的,struct与class是小异大同。struct默认访问权限是public,class是private;class有继承,多态机制,而struct没有。

猜你喜欢

转载自blog.csdn.net/adaptiver/article/details/75452885