C++类与对象:面向对象编程实战指南
C++类与对象
通过清晰示例与最佳实践,掌握如何在C++中使用类和对象封装数据与行为。
为什么使用类?
前几课探讨了函数和变量。随着项目增长,将相关数据和操作分组对可维护性和清晰度至关重要。类让你将数据成员和成员函数捆绑为单一逻辑单元,实现面向对象编程(OOP)——现代C++设计的基石。
举例:房间
设想一个长方形房间。你需要存储其长度、宽度和高度,并计算面积和体积。用类可将这些紧密耦合:
class Room {
public:
double length;
double breadth;
double height;
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
定义类
类用class关键字定义,后接类名和花括号包裹的主体,以分号结尾:
class ClassName {
// data members
// member functions
};
上例中,Room是蓝图。内部变量称数据成员;函数称成员函数。
创建对象
定义类仅指定布局;不分配内存。对象是从蓝图创建的具体实例:
Room room1; // 单个对象
Room room2, room3; // 一次声明多个对象
对象可在任何位置实例化——函数内、其他类内或全局——只需遵守作用域规则。
访问成员
用点(.)运算符调用成员函数或访问数据成员:
room1.length = 5.5;
double area = room1.calculateArea();
示例1:计算房间指标
#include <iostream>
using namespace std;
class Room {
public:
double length;
double breadth;
double height;
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
Room room1;
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;
return 0;
}
输出
Area of Room = 1309 Volume of Room = 25132.8
封装:Public与Private
封装通过控制访问保护数据。声明为private的成员对外部不可见,只能通过公共成员函数访问。
class Test {
private:
int a;
void function1() {}
public:
int b;
void function2() {}
};
下例中数据成员为私有,通过公共方法初始化:
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
void initData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
Room room1;
room1.initData(42.5, 30.8, 19.2);
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;
return 0;
}
输出
Area of Room = 1309 Volume of Room = 25132.8
延伸阅读
权威指南请参考ISO/IEC 14882:2023 C++标准或可信资源如cplusplus.com和cppreference.com。
C语言
- C++结构体与类:嵌入式开发者实战指南
- C# 类与对象:面向对象编程的基石
- 掌握 C# 抽象类与抽象方法:实战指南
- 理解 C# 分部类与分部方法
- 掌握 C# sealed 类与方法:用法、示例与代码安全性能提升
- C++ 友元函数与友元类:突破访问控制的利器
- C++ 类模板实战指南:编写灵活的类型无关代码
- C++ Struct 与 Class 核心差异、语法及最佳实践
- C++存储类别全解析:auto/register/static/extern/mutable作用域与生命周期
- C++日期时间完全指南:ctime库、tm结构体与格式化输出
- C++多态实战指南:虚函数、动态绑定与纯虚函数
- Java 类与对象:实用指南