如大家所知,C++是一种强大且灵活的编程语言,支持多种编程范式,使得开发者能够选择最适合特定问题的解决方案。在实际开发中,面向对象编程、泛型编程、函数式编程和元编程是最常用的几种范式。
今天我们只讲:面向对象编程
不可否认,面向对象编程 是C++ 的核心编程范式,通过类和对象的概念,将数据和操作数据的方法封装在一起,使代码具有更好的组织性和可维护性。
#include <iostream>
#include <string>
class Animal {
public:
Animal(const std::string &name) : name(name) {}
virtual void makeSound() const {
std::cout << name << " makes a sound." << std::endl;
}
protected:
std::string name;
};
class Dog : public Animal {
public:
Dog(const std::string &name) : Animal(name) {}
void makeSound() const override {
std::cout << name << " barks." << std::endl;
}
};
int main() {
Animal *animal = new Dog("Buddy");
animal->makeSound(); // 输出:Buddy barks.
delete animal;
return 0;
}
通过类封装数据和操作,隐藏内部实现细节,只对外暴露接口。而且,如上例所示,Dog
类继承自 Animal
类,并且重写了 makeSound
方法,展示了多态的威力。此外,通过继承,Dog
类复用了 Animal
类的属性 name
,减少了代码重复。
今天的文章分享就到这里了,希望对大家的学习和工作有所帮助~