在C++中,多态可以通过虚函数和纯虚函数来实现。具体有以下几种方式:
class Base {
public:
virtual void print() {
cout << "Base class print function." << endl;
}
};
class Derived : public Base {
public:
void print() override {
cout << "Derived class print function." << endl;
}
};
class Base {
public:
virtual void print() = 0;
};
class Derived : public Base {
public:
void print() override {
cout << "Derived class print function." << endl;
}
};
void print(Base *obj) {
obj->print();
}
Base *basePtr = new Derived();
print(basePtr);
template<typename T>
void print(T *obj) {
obj->print();
}
Base *basePtr = new Derived();
print(basePtr);