01. C++ 面向对象
C++ 在 C 的基础上增加了面向对象编程(OOP)特性。类是 C++ 中封装数据和函数的基本单元。
C++ 的三大特性:
- 封装:将数据和操作数据的函数绑定在一起
- 继承:子类可以继承父类的属性和方法
- 多态:同一接口可以有不同的实现
RAII(资源获取即初始化)是 C++ 的核心编程范式,通过对象的生命周期管理资源。
cpp
#include <iostream>
#include <string>
#include <vector>
class Animal {
protected:
std::string name;
int age;
public:
Animal(const std::string& n, int a) : name(n), age(a) {}
virtual void speak() const {
std::cout << name << " 发出声音" << std::endl;
}
virtual ~Animal() {}
};
class Dog : public Animal {
public:
Dog(const std::string& n, int a) : Animal(n, a) {}
void speak() const override {
std::cout << name << ": 汪汪!" << std::endl;
}
};
int main() {
std::vector<std::unique_ptr<Animal>> animals;
animals.push_back(std::make_unique<Dog>("旺财", 3));
animals.push_back(std::make_unique<Dog>("小黑", 5));
for (const auto& animal : animals) {
animal->speak();
}
return 0;
}知识测验
第 1/4 题正确 0
C++ 中 virtual 关键字的作用是什么?
下一节
下一节 STL 标准库