类的介绍c++

· · 算法·理论

在C++中, 用 "类" 来描述 "对象", 所谓的"对象"是指现实世界中的一切事物。"类"是用来记下事物的相同点和不同点的。

C++中使用关键字 class 来定义类, 其基本形式如下:

//示例1
class 类名
{
    public:
    //公共的行为或属性

    private:
    //公共的行为或属性
};

下面给大家一个标准示例程序来参考哈


//示例2
#include <iostream>
using namespace std;
class Point
{
    public:
    void setPoint(int x, int y) 
    {
        xPos = x;
        yPos = y;
    }
    void printPoint();
    {
    cout<< "x = " << xPos << endl;
    cout<< "y = " << yPos << endl;
    }
    private:
       int xPos;
       int yPos;

}; 
int main()
{
    Point M;
    M.setPoint(10, 20);
    M.printPoint(); 
    return 0;
}
/*运行输出:
x = 10 
y = 20*/