类
类(C++)是结构体(C语言)的升级版。
三个关键概念
封装:把数据和操作数据的方法打包
cpp
class BankAccount {
private: // 私有,外部不能直接访问
double balance; // 余额
public: // 公有,外部可以访问
// 方法可以访问私有数据
void deposit(double money) {
if (money > 0) {
balance += money;
}
}
void withdraw(double money) {
if (money > 0 && money <= balance) {
balance -= money;
}
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount account;
account.deposit(1000); // ✅ 可以
// account.balance = 5000; // ❌ 错误!balance是私有的
printf("余额:%.2f\n", account.getBalance()); // ✅ 通过公有方法访问
return 0;
}构造函数:创建对象时自动调用的函数
cpp
class Person {
private:
char name[20];
int age;
public:
// 构造函数:名字和类名相同,没有返回值
Person() { // 无参构造函数
strcpy(name, "无名");
age = 0;
printf("创建了一个Person对象\n");
}
Person(const char* n, int a) { // 有参构造函数
strcpy(name, n);
age = a;
printf("创建了%s,年龄%d\n", name, age);
}
};
int main() {
Person p1; // 调用无参构造函数
Person p2("张三", 20); // 调用有参构造函数
return 0;
}析构函数:对象销毁时自动调用的函数
cpp
class Student {
private:
char* name; // 使用动态内存
public:
Student(const char* n) {
name = new char[strlen(n) + 1]; // 分配内存
strcpy(name, n);
printf("创建学生:%s\n", name);
}
~Student() { // 析构函数,前面加~
printf("销毁学生:%s\n", name);
delete[] name; // 释放内存
}
};
int main() {
Student s("李四");
// 对象s离开作用域时,自动调用析构函数
return 0;
}例子:一个简单的计算器类
cpp
#include <iostream>
using namespace std;
// 定义一个计算器类
class Calculator {
private:
double result; // 存储结果
public:
// 构造函数
Calculator() {
result = 0;
}
Calculator(double initValue) {
result = initValue;
}
// 各种计算方法
void add(double x) {
result += x;
cout << "加 " << x << ",当前结果:" << result << endl;
}
void subtract(double x) {
result -= x;
cout << "减 " << x << ",当前结果:" << result << endl;
}
void multiply(double x) {
result *= x;
cout << "乘 " << x << ",当前结果:" << result << endl;
}
void divide(double x) {
if (x != 0) {
result /= x;
cout << "除 " << x << ",当前结果:" << result << endl;
} else {
cout << "错误:除数不能为0!" << endl;
}
}
// 获取当前结果
double getResult() {
return result;
}
// 重置计算器
void clear() {
result = 0;
cout << "计算器已重置" << endl;
}
};
int main() {
// 创建计算器对象
Calculator calc(10); // 初始值为10
// 使用对象的方法
calc.add(5); // 10 + 5 = 15
calc.multiply(2); // 15 × 2 = 30
calc.subtract(8); // 30 - 8 = 22
calc.divide(2); // 22 ÷ 2 = 11
cout << "最终结果:" << calc.getResult() << endl;
return 0;
}c
// C语言实现计算器(过程式)
struct Calculator_C {
double result;
};
void initCalculator(struct Calculator_C* calc) {
calc->result = 0;
}
void add(struct Calculator_C* calc, double x) {
calc->result += x;
}
double getResult(struct Calculator_C* calc) {
return calc->result;
}
// 可以看到C++把数据和操作打包在了一起,更直观成员函数写在类外面
cpp
#include <iostream>
#include <string>
class Person {
private:
std::string name;
int age;
public:
// 构造函数 - 在类内定义
Person(const std::string& n, int a) : name(n), age(a) {}
// 成员函数声明
void displayInfo() const;
void celebrateBirthday();
void setName(const std::string& newName);
std::string getName() const;
};
// 成员函数在类外定义(同一个文件内)
void Person::displayInfo() const {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
void Person::celebrateBirthday() {
age++;
std::cout << name << " is now " << age << " years old!" << std::endl;
}
void Person::setName(const std::string& newName) {
name = newName;
}
std::string Person::getName() const {
return name;
}
// 主函数
int main() {
Person person("Alice", 25);
person.displayInfo();
person.celebrateBirthday();
person.setName("Alice Smith");
std::cout << "Updated name: " << person.getName() << std::endl;
return 0;
}cpp
#ifndef PERSON_H
#define PERSON_H
#include <string>
class Person {
private:
std::string name;
int age;
public:
// 构造函数
Person(const std::string& n, int a);
// 成员函数声明
void displayInfo() const;
void celebrateBirthday();
void setName(const std::string& newName);
std::string getName() const;
};
#endif // PERSON_Hcpp
#include "person.h"
#include <iostream>
// 构造函数定义
Person::Person(const std::string& n, int a) : name(n), age(a) {}
// 成员函数定义
void Person::displayInfo() const {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
void Person::celebrateBirthday() {
age++;
std::cout << name << " is now " << age << " years old!" << std::endl;
}
void Person::setName(const std::string& newName) {
name = newName;
}
std::string Person::getName() const {
return name;
}cpp
#include "person.h"
#include <iostream>
int main() {
Person person("Alice", 25);
person.displayInfo();
person.celebrateBirthday();
person.setName("Alice Smith");
std::cout << "Updated name: " << person.getName() << std::endl;
return 0;
}bash
# 编译分离文件版本
g++ -std=c++11 person.cpp main.cpp -o person_program
# 运行程序
./person_program
# 编译单个文件版本
g++ -std=c++11 single-file.cpp -o single_program
./single_program在这个示例中:
- 单个文件实现:所有代码都在一个
.cpp文件中 - 分离文件实现:
person.h:包含类的声明person.cpp:包含类的成员函数定义main.cpp:包含主函数
- 关键特点:
- 使用
#ifndef/#define/#endif防止头文件重复包含 - 类内声明,类外定义成员函数
- 使用
ClassName::functionName()语法定义成员函数 - 使用作用域解析运算符
::
- 使用
这种分离组织方式提高了代码的可维护性,支持模块化开发和分离编译。