类(class)是用户自定义类型,将数据成员与成员函数封装在一起,描述对象的属性与行为。C++ 面向对象编程以类为核心,支持封装、继承与多态。本节说明 class 定义、对象创建、成员访问与 this 指针,后续章节展开构造、访问控制等主题。
类与对象
类是蓝图,对象是类的具体实例。每个对象拥有各自的数据成员副本(静态成员除外),共用同一套成员函数代码。
定义与使用
#include <iostream>
#include <string>
class Book {
public:
std::string title;
int pages = 0;
void describe() const {
std::cout << title << " (" << pages << " pages)\n";
}
};
int main() {
Book b;
b.title = "Notes";
b.pages = 120;
b.describe();
return 0;
}典型输出:Notes (120 pages)。Book b; 定义自动存储期对象;成员用 . 访问。
this 指针
非静态成员函数隐含第一个参数为 this,类型为指向当前对象的指针(const 成员函数中为指向常量对象的指针)。在成员函数内写 title 等价于 this->title。返回当前对象引用时常写 return *this;,便于链式调用:
#include <iostream>
class Counter {
int n = 0;
public:
Counter& add(int x) {
this->n += x; // 与 n += x 相同
return *this; // 返回当前对象,才能接着 .add(...)
}
int get() const {
return this->n;
}
};
int main() {
Counter c;
c.add(1).add(2);
std::cout << c.get() << std::endl;
return 0;
}输出:
3c.add(1) 返回 c 本身,所以可以立刻再 .add(2),n 先加 1 再加 2。
class 与 struct
| 关键字 | 默认成员访问 | 典型用途 |
|---|---|---|
class | private | 含行为与不变量的抽象类型 |
struct | public | 纯数据聚合,见结构体与 class |
默认访问不同,直接访问成员的写法也就不同:
#include <iostream>
struct Point {
int x; // 默认 public,类外可直接读写
int y;
};
class Box {
int w = 3; // 默认 private,类外不能写 b.w
public:
int width() const {
return w;
}
};
int main() {
Point p;
p.x = 1;
p.y = 2;
std::cout << p.x << " " << p.y << "\n";
Box b;
std::cout << b.width() << "\n";
return 0;
}输出:
1 2
3Point 的 x、y 可以直接赋值;Box 的 w 是私有的,只能通过 width() 读取。若在 main 里写 b.w,将无法通过编译。继承时默认访问也不同(class 默认 private 继承,struct 默认 public 继承),见继承。
在堆上创建对象
Book* ptr = new Book();
ptr->title = "Heap";
ptr->describe();
delete ptr;指针使用 -> 访问成员。更推荐使用 std::make_unique<Book>(),见智能指针与动态内存。
成员函数与 const
在成员函数后加 const 表示不修改对象的数据成员(mutable 成员除外)。const 对象只能调用 const 成员函数。只读接口应标记 const,便于与非常量对象重载。
与函数的关系
成员函数可重载;非成员辅助函数可在类外定义,通过引用或指针参数接收对象。运算符重载见运算符重载。
本节说明了类与对象的基本结构。下一节介绍构造函数:对象创建时的初始化。