1.Class的定义
class 类名
{
public:
//公共的行为或属性
private:
//公共的行为或属性
};
注:
- 类名 需要遵循一般的命名规则;
- public 与 private 为属性/方法限制的关键字, private 表示该部分内容是私密的, 不能被外部所访问或调用, 只能被本类内部访问; 而 public 表示公开的属性和方法, 外界可以直接访问或者调用。一般来说类的属性成员都应设置为private, public只留给那些被外界用来调用的函数接口, 但这并非是强制规定, 可以根据需要进行调整;
- 结束部分的分号不能省略。
Example
定义一个点(Point)类, 具有以下属性和方法:
- 属性:
- x坐标
- y坐标
- 方法:
- 1.设置x,y的坐标值;
- 2.输出坐标的信息
class Point
{
public:
void setPoint(int x, int y);
void printPoint();
private:
int xPos;
int yPos;
};
注:
这里仅仅对Point这个class的属性和行为进行了声明,并没有实现它(定义它的方法)
2.实现class的两种方法:
2.1 在定义class的同时,定义里面的member function
Example:
setPoint 和 printPoint
#include <iostream>
using namespace std;
class Point
{
public:
//实现setPoint函数
void setPoint(int x, int y)
{
xPos = x;
yPos = y;
}
//实现printPoint函数
void printPoint()
{
cout<< "x = " << xPos << endl;
cout<< "y = " << yPos << endl;
}
private:
int xPos;
int yPos;
};
int main()
{
Point M; //用定义好的类创建一个对象 点M
M.setPoint(10, 20); //设置 M点 的x,y值
M.printPoint(); //输出 M点 的信息
return 0;
}
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 {
public:
void setPoint(int x, int y); //在类内对成员函数进行声明
void printPoint();
private:
int xPos;
int yPos;
};
////在.cpp file 里进行定义 void Point::setPoint(int x, int y) //通过作用域操作符 ‘::’ 实现setPoint函数 { xPos = x; yPos = y; }
void Point::printPoint() //实现printPoint函数
{
cout<< "x = " << xPos << endl;
cout<< "y = " << yPos << endl;
}
////main.cpp里进行调用 int main() { Point M; //用定义好的类创建一个对象 点M M.setPoint(10, 20); //设置 M点 的x,y值 M.printPoint(); //输出 M点 的信息
return 0;
}
```