当前位置:   article > 正文

十、C++中的类 class与struct的区别_c++class和struct的区别

c++class和struct的区别

面向对象程序设计,需要诸如类和对象这样的概念。

C++支持面向过程、基于对象、面向对象、泛型编程四种

C语言不支持面向对象编程

类是一种将数据和函数组织在一起的方式。

一个函数参数过多,代码不好维护,可创建一个类,一次性包含所有想要的数据,最终作为一个类型。

类必须是唯一的类型名,因为类基本上就是我们创建一个新的变量类型,类使用{}括起来,但是结尾还有一个“;”符号。

由类 类型制成的变量叫做对象,新创建对象的过程叫做实例化。

【结构体struct和类class区别在于权限,class默认private,struct默认public】

访问控制:当创建一个类是,可以指定类中属性的可见性,默认情况下,类中的成员的访问控制都是私有的,只有类内部的函数才能访问这些变量。如果想要在main函数中访问这些变量,类需要被定义为共有的,共有表示被允许在类外访问这些变量。

类的创建与访问:

  1. #include <iostream>
  2. #define LOG(x) std::cout << x << std::endl
  3. class Player
  4. {
  5. public:
  6. int x, y;
  7. int speed = 2;
  8. };
  9. int main()
  10. {
  11. Player player;//使用类,前面是类名,后面随意,类型为Player的player变量
  12. player.x = 5;
  13. std::cin.get();
  14. }

类的移动,编写函数改变X,Y变量,

  1. #include <iostream>
  2. #define LOG(x) std::cout << x << std::endl
  3. class Player
  4. {
  5. public:
  6. int x, y;
  7. int speed = 2;
  8. };
  9. void move(Player& player, int xa, int ya)//接收要移动的Player,引用传递
  10. {
  11. player.x += xa * player.speed;
  12. player.y += ya * player.speed;
  13. }
  14. int main()
  15. {
  16. Player player;
  17. move(player, 1, -1);
  18. std::cin.get();
  19. }

类中可以包含函数,可以移动move函数到类内,类内的函数被称作method(方法&

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/714746
推荐阅读
相关标签
  

闽ICP备14008679号