在C++中,多態(tài)可以通過虛函數(shù)和純虛函數(shù)來實(shí)現(xiàn)。具體有以下幾種方式:
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);