我读了很多关于多态的时间,但在我们使用时仍然会混淆。我试过理解这个例子,但每个例子看起来都一样,我只是想在BASE& amp;派生有相同的功能,对象用作指针吗?
答案 0 :(得分:1)
想象一下这个类层次结构:
class Polygon {
public:
virtual double area();
// Some other member functions
private:
// Some members
};
class Triangle : public Polygon {
public:
virtual double area() { /* code */ }
// Some other member functions
private:
// Some members
};
class Square : public Polygon {
public:
virtual double area() { /* code */ }
// Some other member functions
private:
// Some members
};
您不必使用指针,也可以使用引用。
int main(int argc, char *argv[]) {
Triangle t;
Square s;
Polygon *pt = &t, *ps = &s;
Polygon &rt = t, &rs = s;
pt->area(); // Calls member function area from class Triangle
ps->area(); // Calls member function area from class Square
rt.area(); // Calls member function area from class Triangle
rs.area(); // Calls member function area from class Square
return 0;
}