在 C++ 中,class(类) 是面向对象编程(OOP)的核心概念之一。类用于定义对象的属性和行为,是封装数据和方法的基本单位。以下是 C++ 中类的基础知识。
1. 类的定义
类通过 class
关键字定义,基本语法如下:
class ClassName {// 访问修饰符(public、private、protected)
public:// 公有成员(可以在类外部访问)void publicMethod();private:// 私有成员(只能在类内部访问)int privateData;protected:// 保护成员(可以在派生类中访问)void protectedMethod();
};
2.成员变量和成员函数
class Rectangle {
public:void setDimensions(int w, int h) {width = w;height = h;}int getArea() const {return width * height;}private:int width;int height;
};
3.构造函数和析构函数
class Rectangle {
public:Rectangle(int w, int h) : width(w), height(h) {} // 构造函数~Rectangle() { std::cout << "Rectangle destroyed!" << std::endl; } // 析构函数private:int width;int height;
};
4.this 指针
this 是一个指向当前对象的指针,用于在成员函数中访问当前对象的成员。
class Rectangle {
public:void setWidth(int width) {this->width = width; // 使用 this 指针区分成员变量和参数}private:int width;
};
5.友元
友元函数:可以访问类的私有成员的非成员函数。
友元类:可以访问类的私有成员的另一个类。
class Rectangle {
private:int width;int height;friend void printArea(const Rectangle& rect); // 友元函数
};void printArea(const Rectangle& rect) {std::cout << "Area: " << rect.width * rect.height << std::endl;
}
6.运算符重载
通过重载运算符,可以定义类对象之间的操作。
class Rectangle {
public:Rectangle(int w, int h) : width(w), height(h) {}Rectangle operator+(const Rectangle& other) const { // 重载 + 运算符return Rectangle(width + other.width, height + other.height);}private:int width;int height;
};
7.继承
类可以通过继承扩展功能,支持单继承和多继承。
class Shape {
public:void setColor(const std::string& color) {this->color = color;}protected:std::string color;
};class Rectangle : public Shape {
public:void draw() {std::cout << "Drawing a " << color << " rectangle." << std::endl;}
};
C++ 中的类是面向对象编程的核心,通过类可以实现封装、继承和多态等特性。掌握类的基础知识是学习 C++ 的关键。