📚 面向对象编程概述
什么是面向对象?
面向对象编程(OOP)是一种编程范式,它将数据和操作数据的方法封装在一起,形成类(Class),通过创建对象(Object)来使用。
- ✅ 封装:将数据和行为包装在一起
- ✅ 抽象:隐藏复杂实现,暴露简单接口
- ✅ 继承:子类可以继承父类的特性
- ✅ 多态:同一接口,不同实现
💡 类和对象的关系:
• 类是蓝图/模板(如:汽车设计图)
• 对象是实例(如:具体的某辆汽车)
• 一个类可以创建多个对象
类的定义
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int age;
double score;
void introduce() {
cout << "我叫" << name << ",今年" << age
<< "岁,成绩" << score << endl;
}
void study(int hours) {
cout << name << "学习了" << hours << "小时" << endl;
score += hours * 0.5;
}
};
int main() {
Student stu1;
stu1.name = "张三";
stu1.age = 18;
stu1.score = 85.5;
stu1.introduce();
stu1.study(2);
stu1.introduce();
return 0;
}
访问控制修饰符
class Student {
public:
string name;
void introduce();
private:
double score;
void calculateGrade();
protected:
int studentId;
};
💡 访问控制规则:
• public:公开,任何地方都可访问
• private:私有,只有类内部可访问(默认)
• protected:保护,类和子类可访问
• 良好的封装:数据private,接口public
⚙️ 构造函数和析构函数
构造函数
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int age;
Student() {
name = "未知";
age = 0;
cout << "默认构造函数被调用" << endl;
}
Student(string n, int a) {
name = n;
age = a;
cout << "参数构造函数被调用:" << name << endl;
}
void introduce() {
cout << name << ", " << age << "岁" << endl;
}
};
int main() {
Student stu1;
stu1.introduce();
Student stu2("李四", 19);
stu2.introduce();
return 0;
}
析构函数
#include <iostream>
using namespace std;
class Resource {
public:
string resourceName;
Resource(string name) {
resourceName = name;
cout << "创建资源:" << resourceName << endl;
}
~Resource() {
cout << "释放资源:" << resourceName << endl;
}
};
int main() {
{
Resource res1("文件1");
Resource res2("文件2");
}
cout << "程序继续执行..." << endl;
return 0;
}
初始化列表
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int age;
const int id;
public:
Student(string n, int a, int i)
: name(n), age(a), id(i) {
cout << "学生创建:" << name << endl;
}
void show() {
cout << "ID: " << id << ", 姓名: " << name
<< ", 年龄: " << age << endl;
}
};
int main() {
Student stu("王五", 20, 1001);
stu.show();
return 0;
}
🛠️ 封装和数据隐藏
Getter和Setter方法
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int age;
double score;
public:
string getName() { return name; }
int getAge() { return age; }
double getScore() { return score; }
void setName(string n) { name = n; }
void setAge(int a) {
if (a >= 0 && a <= 150) {
age = a;
} else {
cout << "年龄无效!" << endl;
}
}
void setScore(double s) {
if (s >= 0 && s <= 100) {
score = s;
} else {
cout << "成绩无效!" << endl;
}
}
void show() {
cout << name << ", " << age << "岁, 成绩: " << score << endl;
}
};
int main() {
Student stu;
stu.setName("李四");
stu.setAge(19);
stu.setScore(92.5);
stu.show();
return 0;
}
this指针
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int age;
public:
void setData(string name, int age) {
this->name = name;
this->age = age;
}
Student& setName(string n) {
name = n;
return *this;
}
Student& setAge(int a) {
age = a;
return *this;
}
void show() {
cout << name << ", " << age << "岁" << endl;
}
};
int main() {
Student stu;
stu.setName("王五").setAge(20);
stu.show();
return 0;
}
静态成员
#include <iostream>
using namespace std;
class Counter {
private:
static int count;
public:
Counter() {
count++;
}
static int getCount() {
return count;
}
~Counter() {
count--;
}
};
int Counter::count = 0;
int main() {
cout << "初始计数:" << Counter::getCount() << endl;
Counter c1, c2, c3;
cout << "创建3个对象后:" << Counter::getCount() << endl;
return 0;
}
🚀 实际应用示例
完整的银行账户类
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
string accountHolder;
string accountNumber;
double balance;
public:
BankAccount(string holder, string number, double initialBalance = 0)
: accountHolder(holder), accountNumber(number), balance(initialBalance) {
cout << "账户创建:" << accountHolder << endl;
}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "存款 " << amount << " 成功,余额:" << balance << endl;
}
}
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "取款 " << amount << " 成功,余额:" << balance << endl;
return true;
}
cout << "取款失败!" << endl;
return false;
}
double getBalance() {
return balance;
}
void showInfo() {
cout << "=== 账户信息 ===" << endl;
cout << "户名:" << accountHolder << endl;
cout << "账号:" << accountNumber << endl;
cout << "余额:" << balance << endl;
}
~BankAccount() {
cout << "账户关闭:" << accountHolder << endl;
}
};
int main() {
BankAccount account("张三", "123456789", 1000);
account.showInfo();
account.deposit(500);
account.withdraw(200);
account.showInfo();
return 0;
}
对象数组
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
double score;
public:
Student(string n = "", double s = 0)
: name(n), score(s) {}
string getName() { return name; }
double getScore() { return score; }
void show() {
cout << name << ": " << score << endl;
}
};
int main() {
Student students[3] = {
Student("张三", 90),
Student("李四", 85),
Student("王五", 92)
};
double total = 0;
for (int i = 0; i < 3; i++) {
students[i].show();
total += students[i].getScore();
}
cout << "平均分:" << total / 3 << endl;
return 0;
}
📝 实战练习
📝 理解测试
以下代码中,构造函数的调用顺序是什么?
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "A"; }
~A() { cout << "a"; }
};
class B {
public:
B() { cout << "B"; }
~B() { cout << "b"; }
};
int main() {
A a;
B b;
return 0;
}
选择答案查看解析...
💻 综合挑战
题目:设计一个Rectangle(矩形)类:
1. 私有成员:width(宽)、height(高)
2. 构造函数:支持默认值和无参构造
3. 方法:计算面积、计算周长、显示信息
4. 使用getter/setter访问私有成员
5. 创建多个矩形对象并比较面积
点击"生成代码框架"查看提示...