Skip to content

C++ 类与对象

面向对象编程(Object-Oriented Programming,OOP)是 C++ 的基石,而 类(class)是创建自定义类型的基本构建块,用于模拟现实世界或抽象概念。

可以将类视为创建对象的蓝图。它定义了一种结构,包含数据(称为成员变量或属性)以及可对这些数据执行的操作(称为成员函数或方法)。对象(object)是根据该类蓝图创建出的特定实例。

定义一个类会创建一个新的数据类型。它此时还没有创建任何对象,但它指定了这种类型的对象会是什么样,以及它们可以做什么。

类定义以 class 关键字开头,后跟类名,然后是包含在花括号 {} 中的类体。定义必须以分号 ; 结尾。在类体内部,我们声明成员(变量和函数)。

class Box {
public:
// Constructor (Optional but recommended for initialization)
// 构造函数(可选但推荐用于初始化)
Box(double l = 1.0, double b = 1.0, double h = 1.0)
: length{l}, breadth{b}, height{h} // Modern initializer list
// 现代初始化列表
{}
// Member function to calculate volume
// 计算体积的成员函数
double getVolume() const { // 'const' indicates this function doesn't modify the object
// 'const' 表示此函数不修改对象
return length * breadth * height;
}
// Member function to set dimensions
// 设置尺寸的成员函数
void setDimensions(double l, double b, double h) {
length = l;
breadth = b;
height = h;
}
// Public member variables (Generally prefer private members and public methods)
// 公有成员变量(通常优先使用私有成员和公有方法)
double length;
double breadth;
double height;
// private:
// Member variables are often private for encapsulation
// 成员变量通常设为私有以实现封装
// double length;
// double breadth;
// double height;
}; // Don't forget the semicolon!
// 不要忘记分号!

访问说明符(Access Specifiers):public、private、protected

Section titled “访问说明符(Access Specifiers):public、private、protected”

访问说明符控制类的成员如何被访问:

  • public:声明为 public 的成员可以从类的外部任何地方访问,只要你有一个该类的对象。
  • private:声明为 private 的成员只能由类本身的成员函数和友元函数访问。如果没有指定访问级别,这是默认级别。通常通过将数据成员设为 private 并提供公有成员函数(getter/setter)来控制访问,从而实现封装(Encapsulation)。
  • protected:类似于 private,但 protected 成员也可以被派生类(在继承中使用)的成员函数和友元访问。

类定义后,就可以创建该类的对象(实例),就像声明内置类型的变量一样:

#include <iostream>
// Assume Box class definition from above is here or included
// 假设 Box 类定义在此处或已包含
int main() {
Box smallBox; // Create a Box object using the default constructor (1.0, 1.0, 1.0)
// 使用默认构造函数创建一个 Box 对象 (1.0, 1.0, 1.0)
Box largeBox{10.0, 12.0, 13.0}; // Create using constructor with values (C++11 uniform initialization)
// 使用带值的构造函数创建对象 (C++11 统一初始化)
Box mediumBox(5.0, 6.0, 7.0); // Alternative constructor call syntax
// 另一种构造函数调用语法
// Access public members using the dot operator (.)
// 使用点运算符 (.) 访问公有成员
// mediumBox.length = 5.0; // Direct access if public (as in example)
// 如果是公有成员,可以直接访问(如示例所示)
// mediumBox.breadth = 6.0;
// mediumBox.height = 7.0;
// Call public member functions
// 调用公有成员函数
double smallVolume = smallBox.getVolume();
std::cout << "Volume of smallBox: " << smallVolume << std::endl;
// smallBox 的体积:
double mediumVolume = mediumBox.getVolume();
std::cout << "Volume of mediumBox: " << mediumVolume << std::endl;
// mediumBox 的体积:
largeBox.setDimensions(11.0, 13.0, 14.0); // Modify using a member function
// 使用成员函数修改尺寸
std::cout << "Volume of largeBox after setDimensions: " << largeBox.getVolume() << std::endl;
// setDimensions 后 largeBox 的体积:
// Accessing private members directly would cause a compile-time error:
// 直接访问私有成员会导致编译时错误:
// std::cout << mediumBox.height; // Error if height were private
// 如果 height 是私有的,则会报错
return 0;
}

编译并执行上述代码会产生以下输出:

Volume of smallBox: 1
Volume of mediumBox: 210
Volume of largeBox after setDimensions: 2002

以下是与 C++ 类和对象相关的重要概念的概述:

概念(Concept)描述(Description)
成员函数(Member Functions)在类作用域内定义的函数,用于操作对象的数据成员。它们定义了对象的行为。
访问修饰符(Access Modifiers)控制类成员的可见性和可访问性的关键字(public、private、protected),对于封装至关重要。
构造函数(Constructor)在创建对象时自动调用的特殊成员函数。用于初始化。可以重载。如果没有定义,编译器可能会生成一个默认的。
析构函数(Destructor)在对象超出作用域或被显式删除时自动调用的特殊成员函数(带有 ~ 前缀,例如 ~Box())。用于清理(例如,释放资源)。遵循 RAII 原则。
拷贝/移动语义(Copy/Move Semantics)控制对象如何被拷贝或移动的构造函数和赋值运算符(operator=)。对于资源管理(零/三/五法则)很重要。
友元函数/类(Friend Functions/Classes)被授予特殊访问权限(可访问类的 private 和 protected 成员)的非成员函数或其他类。
this 指针在非静态成员函数内部,this 是指向当前对象实例本身的指针。用于消除歧义或返回对象的引用/指针。
静态成员(Static Members)与类本身关联的成员(数据或函数),而非与单个对象关联。每个类只有一份拷贝。使用类名和作用域解析运算符(例如,ClassName::staticMember)访问。
const 正确性(Const Correctness)使用 const 关键字表示成员函数不修改对象的状态,提高了代码的安全性和清晰度。

理解这些概念对于在 C++ 中进行有效的面向对象编程至关重要。