正文
1. 对象的概念
在面向对象编程中,“对象”是一个真实世界中事物的抽象,包含了数据(即属性)和行为(即方法)。对象是类的实例。比如,“狗”是一个类,每一只具体的狗就是一个对象。
// 示例对象的概念
#include <iostream>
using namespace std;
class Dog {
public:
string name;
int age;
void bark() {
cout << name << " is barking!" << endl;
}
};
int main() {
Dog myDog;
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark(); // 输出: Buddy is barking!
return 0;
}
2. 面向对象和面向过程
面向过程编程强调的是一组指令的顺序执行,而面向对象编程则是围绕“对象”来组织代码。面向对象更注重对象的属性和行为的封装,提高了代码的重用性和可维护性。
3. 类的引入
类是面向对象编程的核心,是对象的模板或蓝图。类描述了对象的属性和行为。
4. 类的定义
类的定义可以通过 class
关键字来实现。类通常包括私有属性和公有方法,用来保护数据不被随意修改。
class Person {
public:
string name;
int age;
void introduce() {
cout << "Hi, I'm " << name << " and I'm " << age << " years old." << endl;
}
};
4.1 两种定义方式
类可以通过声明和实现分开的方式来定义,或者在类定义中直接实现。
// 分离定义
class Car {
public:
void drive();
};
void Car::drive() {
cout << "Driving a car" << endl;
}
// 直接定义
class Bicycle {
public:
void ride() {
cout << "Riding a bicycle" << endl;
}
};
4.2 访问限定符及封装
访问限定符(如 public
、private
和 protected
)用来控制类成员的访问范围。封装是指将数据和方法绑定在一起,并对外隐藏实现细节。
class BankAccount {
private:
double balance;
public:
void deposit(double amount) {
if (amount > 0) balance += amount;
}
void displayBalance() const {
cout << "Balance: " << balance << endl;
}
};
5. 类的实例化
类的实例化即创建类的对象,通过调用构造函数来完成。
Person person;
person.name = "Alice";
person.age = 30;
person.introduce(); // 输出: Hi, I'm Alice and I'm 30 years old.
6. this指针
this
指针指向调用对象自身,可以在成员函数中使用 this
来访问类的成员。
class Rectangle {
private:
int width, height;
public:
Rectangle(int width, int height) {
this->width = width;
this->height = height;
}
void area() const {
cout << "Area: " << width * height << endl;
}
};
结语
感谢您的阅读!期待您的一键三连!欢迎指正!