首页 > 应用开发 > IT综合 > C++面向对象编程核心:类与对象的深度剖析
# C++面向对象编程核心:类与对象的深度剖析
## 面向对象编程基本理念
面向对象编程(OOP)是一种以对象为中心的编程范式,它通过类(Class)定义对象(Object)的蓝图。C++作为一门支持多种编程范式的语言,其面向对象特性在软件设计中扮演着关键角色。
```cpp
// 基础类定义示例
#include <iostream>
#include <string>
class Person {
private:
// 私有成员:实现信息隐藏
std::string name;
int age;
public:
// 公有接口:提供外部访问方法
Person() : name(""), age(0) { // 默认构造函数
std::cout << "Person默认构造函数被调用" << std::endl;
}
// 参数化构造函数
Person(const std::string& n, int a) : name(n), age(a) {
std::cout << "Person参数化构造函数被调用" << std::endl;
}
// 析构函数
~Person() {
std::cout << "Person析构函数被调用: " << name << std::endl;
}
// 成员函数:操作对象状态
void displayInfo() const {
std::cout << "姓名: " << name << ", 年龄: " << age << std::endl;
}
void setName(const std::string& n) {
name = n;
}
std::string getName() const {
return name;
}
void setAge(int a) {
if (a >= 0 && a <= 150) {
age = a;
}
}
int getAge() const {
return age;
}
};
```
## 类成员访问控制
### 三种访问修饰符
```cpp
class AccessControlDemo {
public: // 公有成员:任何地方都可以访问
int publicVar;
void publicMethod() {
std::cout << "公有方法" << std::endl;
}
protected: // 保护成员:仅类内和派生类可以访问
int protectedVar;
void protectedMethod() {
std::cout << "保护方法" << std::endl;
}
private: // 私有成员:仅类内可以访问
int privateVar;
void privateMethod() {
std::cout << "私有方法" << std::endl;
}
public:
void testAccess() {
publicVar = 1; // ✓ 可以访问
protectedVar = 2; // ✓ 可以访问
privateVar = 3; // ✓ 可以访问
publicMethod(); // ✓ 可以调用
protectedMethod(); // ✓ 可以调用
privateMethod(); // ✓ 可以调用
}
};
// 派生类访问测试
class Derived : public AccessControlDemo {
public:
void testDerivedAccess() {
publicVar = 10; // ✓ 可以访问(继承为public)
protectedVar = 20; // ✓ 可以访问(继承为protected)
// privateVar = 30; // ✗ 错误:不可访问
publicMethod(); // ✓ 可以调用
protectedMethod(); // ✓ 可以调用
// privateMethod(); // ✗ 错误:不可调用
}
};
void externalAccessTest() {
AccessControlDemo obj;
obj.publicVar = 100; // ✓ 可以访问
obj.publicMethod(); // ✓ 可以调用
// obj.protectedVar = 200; // ✗ 错误:外部不可访问
// obj.privateVar = 300; // ✗ 错误:外部不可访问
}
```
## 构造函数与析构函数
### 构造函数类型与使用
```cpp
class ComplexObject {
private:
std::string* data;
int size;
public:
// 1. 默认构造函数
ComplexObject() : data(nullptr), size(0) {
std::cout << "默认构造函数" << std::endl;
}
// 2. 参数化构造函数
ComplexObject(const std::string& value, int s) : size(s) {
std::cout << "参数化构造函数" << std::endl;
if (size > 0) {
data = new std::string[size];
for (int i = 0; i < size; ++i) {
data[i] = value + "_" + std::to_string(i);
}
} else {
data = nullptr;
}
}
// 3. 拷贝构造函数
ComplexObject(const ComplexObject& other) : size(other.size) {
std::cout << "拷贝构造函数" << std::endl;
if (size > 0) {
data = new std::string[size];
for (int i = 0; i < size; ++i) {
data[i] = other.data[i];
}
} else {
data = nullptr;
}
}
// 4. 移动构造函数 (C++11)
ComplexObject(ComplexObject&& other) noexcept
: data(other.data), size(other.size) {
std::cout << "移动构造函数" << std::endl;
other.data = nullptr;
other.size = 0;
}
// 5. 委托构造函数 (C++11)
ComplexObject(const std::string& value)
: ComplexObject(value, 1) { // 委托给参数化构造函数
std::cout << "委托构造函数" << std::endl;
}
// 析构函数
~ComplexObject() {
std::cout << "析构函数,size=" << size << std::endl;
delete[] data;
}
// 显示拷贝赋值运算符
ComplexObject& operator=(const ComplexObject& other) {
std::cout << "拷贝赋值运算符" << std::endl;
if (this != &other) {
delete[] data;
size = other.size;
if (size > 0) {
data = new std::string[size];
for (int i = 0; i < size; ++i) {
data[i] = other.data[i];
}
} else {
data = nullptr;
}
}
return *this;
}
// 显示移动赋值运算符 (C++11)
ComplexObject& operator=(ComplexObject&& other) noexcept {
std::cout << "移动赋值运算符" << std::endl;
if (this != &other) {
delete[] data;
data = other.data;
size = other.size;
other.data = nullptr;
other.size = 0;
}
return *this;
}
void display() const {
std::cout << "对象内容: ";
if (size > 0 && data) {
for (int i = 0; i < size; ++i) {
std::cout << data[i] << " ";
}
} else {
std::cout << "(空)";
}
std::cout << std::endl;
}
};
void constructor_demo() {
std::cout << "=== 构造函数演示 ===" << std::endl;
// 调用默认构造函数
ComplexObject obj1;
// 调用参数化构造函数
ComplexObject obj2("Hello", 3);
obj2.display();
// 调用拷贝构造函数
ComplexObject obj3 = obj2;
obj3.display();
// 调用委托构造函数
ComplexObject obj4("Test");
obj4.display();
// 拷贝赋值
ComplexObject obj5;
obj5 = obj2;
obj5.display();
// 移动构造
ComplexObject obj6 = std::move(obj2);
obj6.display();
// obj2现在处于有效但未定义状态
std::cout << "=== 演示结束 ===" << std::endl;
}
```
### 初始化列表的重要性
```cpp
class InitializationDemo {
private:
const int constMember; // const成员必须使用初始化列表
int& refMember; // 引用成员必须使用初始化列表
std::string name;
int value;
static int staticMember; // 静态成员
public:
// 错误:不能在构造函数体内初始化const或引用成员
// InitializationDemo(int cm, int& rm) {
// constMember = cm; // 编译错误!
// refMember = rm; // 编译错误!
// }
// 正确:使用成员初始化列表
InitializationDemo(int cm, int& rm, const std::string& n, int v)
: constMember(cm), // const成员初始化
refMember(rm), // 引用成员初始化
name(n), // 普通成员初始化
value(v) // 可以省略,但推荐使用
{
// 构造函数体内可以进行其他初始化
// 但const和引用成员必须在初始化列表中初始化
}
// 构造函数重载
InitializationDemo()
: constMember(0),
refMember(constMember), // 可以引用同一对象的成员
name("default"),
value(0)
{
// 空构造函数体
}
// 静态成员函数
static void setStatic(int value) {
staticMember = value;
}
static int getStatic() {
return staticMember;
}
void display() const {
std::cout << "constMember: " << constMember
<< ", refMember: " << refMember
<< ", name: " << name
<< ", value: " << value
<< ", staticMember: " << staticMember << std::endl;
}
};
// 静态成员定义(必须在类外)
int InitializationDemo::staticMember = 0;
// 测试初始化列表
void initialization_list_demo() {
int externalVar = 100;
InitializationDemo obj1(10, externalVar, "测试对象", 42);
obj1.display();
// 修改外部变量会影响引用成员
externalVar = 200;
obj1.display(); // refMember也会改变
// 测试静态成员
InitializationDemo::setStatic(999);
InitializationDemo obj2;
obj2.display(); // staticMember对所有实例共享
}
```
## 静态成员与常量成员
```cpp
class Account {
private:
std::string owner;
double balance;
// 静态成员:类级别共享
static double interestRate; // 静态数据成员
static int accountCount; // 静态计数器
// 常量成员:对象级别,但值固定
const int accountId; // 常量数据成员
static const int MAX_BALANCE = 1000000; // 静态常量
public:
Account(const std::string& ownerName, double initialBalance)
: owner(ownerName),
balance(initialBalance),
accountId(++accountCount) // 使用计数器初始化常量成员
{
std::cout << "创建账户 #" << accountId
<< ",户主: " << owner << std::endl;
}
~Account() {
std::cout << "关闭账户 #" << accountId
<< ",户主: " << owner << std::endl;
}
// 实例方法:操作特定对象
void deposit(double amount) {
if (amount > 0 && balance + amount <= MAX_BALANCE) {
balance += amount;
std::cout << "存款 " << amount
<< ",新余额: " << balance << std::endl;
}
}
bool withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
std::cout << "取款 " << amount
<< ",新余额: " << balance << std::endl;
return true;
}
return false;
}
void display() const {
std::cout << "账户 #" << accountId
<< ",户主: " << owner
<< ",余额: " << balance
<< ",利率: " << interestRate * 100 << "%" << std::endl;
}
// 静态方法:类级别操作
static void setInterestRate(double newRate) {
if (newRate >= 0 && newRate <= 0.1) { // 限制利率范围
interestRate = newRate;
std::cout << "利率调整为: " << newRate * 100 << "%" << std::endl;
}
}
static double getInterestRate() {
return interestRate;
}
static int getAccountCount() {
return accountCount;
}
// 常量方法:不修改对象状态
int getAccountId() const {
return accountId;
}
const std::string& getOwner() const {
return owner;
}
double getBalance() const {
return balance;
}
// 友元函数声明
friend void transfer(Account& from, Account& to, double amount);
};
// 静态成员定义和初始化(必须在类外)
double Account::interestRate = 0.03; // 默认利率3%
int Account::accountCount = 0; // 账户计数器从0开始
// 友元函数实现
void transfer(Account& from, Account& to, double amount) {
if (from.withdraw(amount)) {
to.deposit(amount);
std::cout << "转账成功: " << amount
<< " 从 " << from.owner
<< " 到 " << to.owner << std::endl;
} else {
std::cout << "转账失败: 余额不足" << std::endl;
}
}
// 使用静态成员和常量成员
void static_and_const_demo() {
std::cout << "当前账户数量: " << Account::getAccountCount() << std::endl;
std::cout << "当前利率: " << Account::getInterestRate() * 100 << "%" << std::endl;
// 创建账户
Account alice("Alice", 5000);
Account bob("Bob", 3000);
alice.display();
bob.display();
// 修改利率(影响所有账户)
Account::setInterestRate(0.035); // 调整为3.5%
// 进行交易
alice.deposit(1000);
bob.withdraw(500);
// 使用友元函数转账
transfer(alice, bob, 2000);
// 显示账户信息
std::cout << "\n所有账户信息:" << std::endl;
alice.display();
bob.display();
std::cout << "总账户数量: " << Account::getAccountCount() << std::endl;
<"pe.jsnjz.cn"><"tz.csxthr.com"><"7s.zhaiLimao.com">
}
```
## 对象组合与聚合
```cpp
// 引擎类
class Engine {
private:
int horsepower;
bool isRunning;
public:
Engine(int hp) : horsepower(hp), isRunning(false) {}
void start() {
if (!isRunning) {
isRunning = true;
std::cout << "引擎启动,马力: " << horsepower << "HP" << std::endl;
}
}
void stop() {
if (isRunning) {
isRunning = false;
std::cout << "引擎停止" << std::endl;
}
}
bool getIsRunning() const { return isRunning; }
int getHorsepower() const { return horsepower; }
};
// 车轮类
class Wheel {
private:
double pressure; // 胎压
std::string position; // 位置
public:
Wheel(const std::string& pos, double press = 32.0)
: position(pos), pressure(press) {}
void inflate(double amount) {
pressure += amount;
std::cout << position << "轮胎充气,新胎压: " << pressure << " PSI" << std::endl;
}
double getPressure() const { return pressure; }
const std::string& getPosition() const { return position; }
};
// 汽车类:组合和聚合示例
class Car {
private:
// 组合关系:汽车拥有引擎,引擎生命周期与汽车一致
Engine engine;
// 聚合关系:汽车包含车轮,但车轮可以独立存在
std::vector<Wheel> wheels;
std::string model;
std::string owner;
public:
// 构造函数:初始化组合成员
Car(const std::string& modelName, const std::string& ownerName, int engineHP)
: engine(engineHP), // 调用Engine构造函数
model(modelName),
owner(ownerName)
{
// 初始化聚合成员
wheels.emplace_back("前左", 32.0);
wheels.emplace_back("前右", 32.0);
wheels.emplace_back("后左", 32.0);
wheels.emplace_back("后右", 32.0);
std::cout << "创建汽车: " << model
<< ",车主: " << owner << std::endl;
}
void start() {
engine.start();
if (engine.getIsRunning()) {
std::cout << owner << "的" << model << "准备出发" << std::endl;
}
}
void stop() {
engine.stop();
std::cout << owner << "的" << model << "已停车" << std::endl;
}
void checkTires() {
std::cout << "检查轮胎胎压:" << std::endl;
for (const auto& wheel : wheels) {
std::cout << " " << wheel.getPosition()
<< ": " << wheel.getPressure() << " PSI" << std::endl;
}
}
void inflateAllTires(double pressure) {
std::cout << "为所有轮胎充气到" << pressure << " PSI" << std::endl;
for (auto& wheel : wheels) {
wheel.inflate(pressure - wheel.getPressure());
}
}
void displayInfo() const {
std::cout << "\n汽车信息:" << std::endl;
std::cout << " 型号: " << model << std::endl;
std::cout << " 车主: " << owner << std::endl;
std::cout << " 引擎马力: " << engine.getHorsepower() << "HP" << std::endl;
std::cout << " 引擎状态: " << (engine.getIsRunning() ? "运行中" : "已停止") << std::endl;
std::cout << " 轮胎数量: " << wheels.size() << std::endl;
}
// 获取轮胎的引用(演示聚合关系)
Wheel& getWheel(size_t index) {
if (index < wheels.size()) {
return wheels[index];
}
throw std::out_of_range("轮胎索引越界");
}
// 更换轮胎(演示聚合关系)
void replaceWheel(size_t index, const Wheel& newWheel) {
if (index < wheels.size()) {
std::cout << "更换" << wheels[index].getPosition() << "轮胎" << std::endl;
wheels[index] = newWheel;
}
}
};
// 车库类:演示对象集合
class Garage {
private:
std::vector<Car> cars;
std::string name;
public:
explicit Garage(const std::string& garageName) : name(garageName) {}
void addCar(const Car& car) {
cars.push_back(car);
std::cout << "将" << car.getOwner() << "的汽车加入车库" << std::endl;
}
void showAllCars() const {
std::cout << "\n=== " << name << "车库中的汽车 ===" << std::endl;
for (const auto& car : cars) {
car.displayInfo();
}
}
void startAllCars() {
std::cout << "\n启动所有汽车:" << std::endl;
for (auto& car : cars) {
car.start();
}
}
void stopAllCars() {
std::cout << "\n停止所有汽车:" << std::endl;
for (auto& car : cars) {
car.stop();
}
}
};
// 对象组合与聚合演示
void composition_aggregation_demo() {
std::cout << "=== 对象组合与聚合演示 ===" << std::endl;
// 创建汽车对象
Car car1("Toyota Camry", "张三", 180);
Car car2("Honda Accord", "李四", 200);
// 操作汽车
car1.displayInfo();
car1.start();
car1.checkTires();
car1.inflateAllTires(35.0);
car1.stop();
std::cout << "\n";
car2.displayInfo();
car2.start();
// 更换轮胎(演示聚合)
Wheel newWheel("前左", 36.0);
car2.replaceWheel(0, newWheel);
car2.checkTires();
// 使用车库管理多辆汽车
Garage myGarage("我的车库");
myGarage.addCar(car1);
myGarage.addCar(car2);
myGarage.showAllCars();
myGarage.startAllCars();
myGarage.stopAllCars();
std::cout << "=== 演示结束 ===" << std::endl;
}
```
## this指针与操作符重载
```cpp
class ComplexNumber {
private:
double real;
double imaginary;
public:
ComplexNumber(double r = 0.0, double i = 0.0)
: real(r), imaginary(i) {}
// 使用this指针访问成员
void setReal(double r) {
this->real = r; // 使用this明确指示
}
void setImaginary(double i) {
this->imaginary = i;
}
// 返回this指针支持链式调用
ComplexNumber& add(double r, double i) {
real += r;
imaginary += i;
return *this; // 返回当前对象的引用
}
ComplexNumber& subtract(double r, double i) {
real -= r;
imaginary -= i;
return *this;
}
// 操作符重载:加法
ComplexNumber operator+(const ComplexNumber& other) const {
return ComplexNumber(real + other.real,
imaginary + other.imaginary);
}
// 操作符重载:减法
ComplexNumber operator-(const ComplexNumber& other) const {
return ComplexNumber(real - other.real,
imaginary - other.imaginary);
}
// 操作符重载:复合加法赋值
ComplexNumber& operator+=(const ComplexNumber& other) {
real += other.real;
imaginary += other.imaginary;
return *this;
}
// 操作符重载:相等比较
bool operator==(const ComplexNumber& other) const {
return (real == other.real) && (imaginary == other.imaginary);
}
bool operator!=(const ComplexNumber& other) const {
return !(*this == other);
}
// 操作符重载:输出流
friend std::ostream& operator<<(std::ostream& os,
const ComplexNumber& cn) {
os << cn.real;
if (cn.imaginary >= 0) {
os << " + " << cn.imaginary << "i";
} else {
os << " - " << -cn.imaginary << "i";
}
return os;
}
// 操作符重载:输入流
friend std::istream& operator>>(std::istream& is, ComplexNumber& cn) {
std::cout << "请输入实部: ";
is >> cn.real;
std::cout << "请输入虚部: ";
is >> cn.imaginary;
return is;
}
// 前置递增操作符
ComplexNumber& operator++() {
++real;
return *this;
}
// 后置递增操作符
ComplexNumber operator++(int) {
ComplexNumber temp = *this;
++real;
return temp;
}
// 类型转换操作符
operator double() const {
return std::sqrt(real * real + imaginary * imaginary);
<"0l.yunruiwater.cn"><"6j.sxyicheng.cn"><"3b.jsnjz.cn">
}
void display() const {
std::cout << *this << std::endl;
}
};
// this指针和操作符重载演示
void this_and_operator_demo() {
std::cout << "=== this指针与操作符重载演示 ===" << std::endl;
ComplexNumber c1(3.0, 4.0);
ComplexNumber c2(1.5, 2.5);
std::cout << "c1 = " << c1 << std::endl;
std::cout << "c2 = " << c2 << std::endl;
// 使用操作符重载
ComplexNumber c3 = c1 + c2;
std::cout << "c1 + c2 = " << c3 << std::endl;
ComplexNumber c4 = c1 - c2;
std::cout << "c1 - c2 = " << c4 << std::endl;
// 链式调用
c1.add(1.0, 1.0).subtract(0.5, 0.5);
std::cout << "链式操作后 c1 = " << c1 << std::endl;
// 复合赋值操作符
c2 += c1;
std::cout << "c2 += c1 后 c2 = " << c2 << std::endl;
// 比较操作符
std::cout << "c1 == c2? " << (c1 == c2 ? "是" : "否") << std::endl;
std::cout << "c1 != c2? " << (c1 != c2 ? "是" : "否") << std::endl;
// 递增操作符
++c1;
std::cout << "++c1 = " << c1 << std::endl;
ComplexNumber c5 = c2++;
std::cout << "c2++ = " << c2 << " (临时值: " << c5 << ")" << std::endl;
// 类型转换
double magnitude = static_cast<double>(c1);
std::cout << "c1的模 = " << magnitude << std::endl;
// 输入输出操作符
ComplexNumber c6;
// std::cin >> c6; // 可以启用输入
// std::cout << "输入的数: " << c6 << std::endl;
std::cout << "=== 演示结束 ===" << std::endl;
}
```
C++面向对象编程的核心在于正确理解类与对象的关系。类作为对象的蓝图,通过访问控制实现信息隐藏,通过构造函数控制对象初始化,通过成员函数定义对象行为。掌握静态成员、常量成员、this指针和操作符重载等高级特性,能够编写出更安全、更高效、更易维护的面向对象代码。这些基础概念是构建复杂C++应用程序的基石。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3108975/ ,如需转载,请注明出处,否则将追究法律责任。