1.Class的定义

  1. class 类名
  2. {
  3. public:
  4. //公共的行为或属性
  5. private:
  6. //公共的行为或属性
  7. };

注:

  1. 类名 需要遵循一般的命名规则;
  2. public 与 private 为属性/方法限制的关键字, private 表示该部分内容是私密的, 不能被外部所访问或调用, 只能被本类内部访问; 而 public 表示公开的属性和方法, 外界可以直接访问或者调用。一般来说类的属性成员都应设置为private, public只留给那些被外界用来调用的函数接口, 但这并非是强制规定, 可以根据需要进行调整;
  3. 结束部分的分号不能省略。

Example
定义一个点(Point)类, 具有以下属性和方法:

  1. - 属性:
  2. - x坐标
  3. - y坐标
  4. - 方法:
  5. - 1.设置x,y的坐标值;
  6. - 2.输出坐标的信息
  1. class Point
  2. {
  3. public:
  4. void setPoint(int x, int y);
  5. void printPoint();
  6. private:
  7. int xPos;
  8. int yPos;
  9. };
  10. 注:
  11. 这里仅仅对Point这个class的属性和行为进行了声明,并没有实现它(定义它的方法)

2.实现class的两种方法:

2.1 在定义class的同时,定义里面的member function

Example:
setPoint 和 printPoint

  1. #include <iostream>
  2. using namespace std;
  3. class Point
  4. {
  5. public:
  6. //实现setPoint函数
  7. void setPoint(int x, int y)
  8. {
  9. xPos = x;
  10. yPos = y;
  11. }
  12. //实现printPoint函数
  13. void printPoint()
  14. {
  15. cout<< "x = " << xPos << endl;
  16. cout<< "y = " << yPos << endl;
  17. }
  18. private:
  19. int xPos;
  20. int yPos;
  21. };
  22. int main()
  23. {
  24. Point M; //用定义好的类创建一个对象 点M
  25. M.setPoint(10, 20); //设置 M点 的x,y值
  26. M.printPoint(); //输出 M点 的信息
  27. return 0;
  28. }

2.2 通过 : : 作用域操作符,在header file之外定义class里面的member function

Example:

  • 第一步:在header file的class内 声明member function
  • 第二步:在class在.cpp file里 定义member function ```cpp

    include

    using namespace std; ////header file class Point {

    1. public:
    2. void setPoint(int x, int y); //在类内对成员函数进行声明
    3. void printPoint();
    4. private:
    5. int xPos;
    6. int yPos;

    };

////在.cpp file 里进行定义 void Point::setPoint(int x, int y) //通过作用域操作符 ‘::’ 实现setPoint函数 { xPos = x; yPos = y; }

  1. void Point::printPoint() //实现printPoint函数
  2. {
  3. cout<< "x = " << xPos << endl;
  4. cout<< "y = " << yPos << endl;
  5. }

////main.cpp里进行调用 int main() { Point M; //用定义好的类创建一个对象 点M M.setPoint(10, 20); //设置 M点 的x,y值 M.printPoint(); //输出 M点 的信息

  1. return 0;
  2. }

```