在C++中,类方法的继承和多态主要通过基类(父类)和派生类(子类)之间的关系来实现
继承是面向对象编程的一个重要特性,它允许一个类(派生类)继承另一个类(基类)的属性和方法。这样,派生类可以重用基类的代码,同时还可以添加或覆盖基类的方法。
#include<iostream>
class Base {
public:
void print() {
std::cout << "Base class method"<< std::endl;
}
};
class Derived : public Base {
public:
void print() {
std::cout << "Derived class method"<< std::endl;
}
};
int main() {
Base *base = new Base();
base->print(); // 输出 "Base class method"
Derived *derived = new Derived();
derived->print(); // 输出 "Derived class method"
Base *base_ptr = new Derived();
base_ptr->print(); // 输出 "Base class method",因为print()方法不是虚函数
delete base;
delete derived;
delete base_ptr;
return 0;
}
多态是指允许使用基类指针或引用来操作派生类对象。为了实现多态,我们需要将基类的方法声明为虚函数(virtual)。这样,当通过基类指针或引用调用该方法时,会根据实际对象的类型来调用相应的方法。
#include<iostream>
class Base {
public:
virtual void print() {
std::cout << "Base class method"<< std::endl;
}
};
class Derived : public Base {
public:
void print() override {
std::cout << "Derived class method"<< std::endl;
}
};
int main() {
Base *base = new Base();
base->print(); // 输出 "Base class method"
Derived *derived = new Derived();
derived->print(); // 输出 "Derived class method"
Base *base_ptr = new Derived();
base_ptr->print(); // 输出 "Derived class method",因为print()方法是虚函数
delete base;
delete derived;
delete base_ptr;
return 0;
}
在这个例子中,我们将Base
类的print()
方法声明为虚函数。当我们通过Base
类指针调用print()
方法时,如果实际对象是Derived
类的实例,那么将调用Derived
类的print()
方法。这就是多态的体现。