类(Class) 是面向对象编程(OOP)中的一个核心概念,它定义了对象的属性和方法。类是一种用户定义的数据类型,用于描述具有相同属性(也称为数据成员或字段)和相同行为(也称为成员函数或方法)的一组对象的集合。
一个简单的类定义示例(以C++为例)如下:
cpp复制代码
// 定义一个名为"Rectangle"的类 | |
class Rectangle { | |
private: // 私有成员,只能在类内部访问 | |
int width; | |
int height; | |
public: // 公有成员,可以在类外部访问 | |
// 构造函数 | |
Rectangle(int w, int h) : width(w), height(h) {} | |
// 获取宽度的成员函数 | |
int getWidth() const { | |
return width; | |
} | |
// 获取高度的成员函数 | |
int getHeight() const { | |
return height; | |
} | |
// 计算面积的成员函数 | |
int getArea() const { | |
return width * height; | |
} | |
// 设置宽度的成员函数 | |
void setWidth(int w) { | |
width = w; | |
} | |
// 设置高度的成员函数 | |
void setHeight(int h) { | |
height = h; | |
} | |
}; | |
// 在类外部使用Rectangle类 | |
int main() { | |
// 创建一个Rectangle对象,并初始化其宽度和高度 | |
Rectangle rect(10, 5); | |
// 调用成员函数获取并打印面积 | |
std::cout << "Area of rectangle: " << rect.getArea() << std::endl; | |
// 修改矩形的宽度 | |
rect.setWidth(15); | |
// 再次打印面积,这次应该已经改变了 | |
std::cout << "Area of rectangle after modifying width: " << rect.getArea() << std::endl; | |
return 0; | |
} |
在这个例子中,我们定义了一个名为Rectangle
的类,它有两个私有数据成员(width
和height
),以及几个公有成员函数(包括构造函数、获取和设置宽度和高度的函数,以及计算面积的函数)。在main
函数中,我们创建了一个Rectangle
对象rect
,并调用了它的成员函数来操作这个对象。