1. C++中的类与对象基础解析
在C++的世界里,类和对象就像建筑蓝图与实体房屋的关系。类(Class)是程序员自定义的数据类型,它不仅仅包含数据成员,还包含操作这些数据的成员函数。而对象(Object)则是根据这个蓝图具体创建出来的实例。
1.1 类的声明与定义
一个典型的C++类声明如下所示:
cpp复制class Student {
private:
std::string name; // 私有数据成员
int age;
public:
// 构造函数
Student(std::string n, int a) : name(n), age(a) {}
// 成员函数
void displayInfo() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
// setter方法
void setName(std::string n) {
name = n;
}
// getter方法
std::string getName() {
return name;
}
};
这个Student类展示了几个关键特性:
- 使用
private和public访问修饰符控制成员的可见性 - 包含数据成员(name, age)和成员函数(displayInfo, setName, getName)
- 提供了构造函数来初始化对象
提示:良好的类设计应该遵循"信息隐藏"原则,将数据成员设为private,通过public方法提供访问接口。
1.2 对象的创建与使用
创建类的对象有多种方式:
cpp复制// 栈上创建对象
Student stu1("Alice", 20);
// 堆上创建对象
Student* stu2 = new Student("Bob", 21);
// 使用对象
stu1.displayInfo();
stu2->displayInfo();
// 不要忘记删除堆对象
delete stu2;
对象的使用需要注意内存管理问题:
- 栈对象在离开作用域时自动销毁
- 堆对象需要手动管理,使用new分配,delete释放
- 现代C++更推荐使用智能指针管理堆对象
2. 面向对象三大特性实现
2.1 封装(Encapsulation)
封装是面向对象编程的基石。在C++中,我们通过访问修饰符实现封装:
cpp复制class BankAccount {
private:
double balance; // 私有数据,外部无法直接访问
public:
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
bool withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
return true;
}
return false;
}
double getBalance() {
return balance;
}
};
封装的好处包括:
- 保护数据不被意外修改
- 隐藏实现细节,降低耦合度
- 便于修改内部实现而不影响外部代码
2.2 继承(Inheritance)
C++支持多种继承方式:
cpp复制// 基类
class Shape {
protected:
int width, height;
public:
Shape(int w, int h) : width(w), height(h) {}
virtual double area() = 0; // 纯虚函数
};
// 派生类
class Rectangle : public Shape {
public:
Rectangle(int w, int h) : Shape(w, h) {}
double area() override {
return width * height;
}
};
class Triangle : public Shape {
public:
Triangle(int w, int h) : Shape(w, h) {}
double area() override {
return width * height / 2.0;
}
};
继承使用时需要注意:
- 公有继承(is-a关系)最常用
- 谨慎使用多重继承,容易导致"菱形继承"问题
- 虚函数实现运行时多态
2.3 多态(Polymorphism)
多态允许我们通过基类指针或引用操作派生类对象:
cpp复制void printArea(Shape* shape) {
std::cout << "Area: " << shape->area() << std::endl;
}
int main() {
Rectangle rect(10, 20);
Triangle tri(10, 20);
printArea(&rect); // 输出200
printArea(&tri); // 输出100
return 0;
}
实现多态的关键:
