日志11
面向对象(Object-Oriented Programming, OOP)是编程的一种思想或范式,而面向对象的C++指的是利用C++语言来实现这一思想。C++是一门支持面向对象编程的语言,它的面向对象特性可以用来组织和管理复杂程序。
面向对象的核心概念
面向对象编程主要包括以下几个核心概念:
1. 类(Class)和对象(Object)
- 类:类是对一类事物的抽象描述,类似于蓝图或模板,定义了属性(成员变量)和行为(成员函数)。
- 对象:对象是类的实例,是实际存在的具体事物。例如,一个
Car类可以有具体的对象car1和car2。
class Car {
public:
string brand;
int speed;
void drive() {
cout << brand << " is driving at " << speed << " km/h." << endl;
}
};
int main() {
Car car1;
car1.brand = "Toyota";
car1.speed = 120;
car1.drive(); // Toyota is driving at 120 km/h.
return 0;
}
2. 封装(Encapsulation)
封装指将数据和操作数据的方法绑定在一起,并通过访问权限控制(private、protected、public)来保护数据的安全性。
class Account {
private:
double balance; // 私有成员,外部不能直接访问
public:
void deposit(double amount) {
if (amount > 0) balance += amount;
}
double getBalance() const {
return balance;
}
};
3. 继承(Inheritance)
继承允许一个类从另一个类中获取属性和方法,支持代码复用和扩展功能。
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};
class Dog : public Animal { // Dog类继承Animal类
public:
void bark() {
cout << "The dog barks." << endl;
}
};
int main() {
Dog myDog;
myDog.eat(); // 调用继承的方法
myDog.bark(); // 调用Dog类的方法
return 0;
}
4. 多态(Polymorphism)
多态允许同一个接口表现出不同的行为,分为编译时多态(函数重载和运算符重载)和运行时多态(通过虚函数实现)。
class Animal {
public:
virtual void sound() {
cout << "Some generic animal sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Woof!" << endl;
}
};
int main() {
Animal* animal = new Dog();
animal->sound(); // 输出:Woof!
delete animal;
return 0;
}
5. 抽象(Abstraction)
抽象指隐藏对象的复杂实现细节,只提供必要的接口。例如,通过纯虚函数实现抽象类。
class Shape {
public:
virtual double area() const = 0; // 纯虚函数
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return 3.14159 * radius * radius;
}
};

查看9道真题和解析