在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);