【发布时间】:2016-04-29 17:42:44
【问题描述】:
首先,我想说我搜索了类似的问题,但答案似乎集中在不同的事情上。
我开始学习 C++,但我无法理解究竟什么是多态。我写了两个不同的程序。
首先,我不使用虚方法或指向对象的指针。
在第二个中,我使用了一个虚拟方法(区域)和一个带有指向对象的指针的数组。
我知道第二个程序正在使用多态性(父类指针用于指向子类对象)。
但是由于第一个程序通过覆盖函数区域产生完全相同的结果,它是否也被认为是使用多态性?
计划 1
#include <iostream>
using namespace std;
class Polygon {
protected:
float base;
float height;
public:
Polygon(): base(0), height(0) {}
Polygon(float b, float h): base(b), height(h) {}
float area() {return -1;}
};
class Triangle:public Polygon {
public:
Triangle(): Polygon() {}
Triangle(float b, float h): Polygon(b,h) {}
float area() {return base*height/2;}
};
class Rectangle:public Polygon {
public:
Rectangle(): Polygon() {}
Rectangle(float b, float h): Polygon(b,h) {}
float area() {return base*height;}
};
int main() {
//Overriding area method without pointers
Triangle t1, t2(10,10);
Rectangle r1, r2(5,5);
cout<<t1.area()<<endl; //Output: 0
cout<<t2.area()<<endl; //Output: 50
cout<<r1.area()<<endl; //Output: 0
cout<<r2.area()<<endl; //Output: 25
cout<<t1.Polygon::area()<<endl; //Output: -1
}
方案 2
#include <iostream>
using namespace std;
class Polygon {
protected:
float base;
float height;
public:
Polygon(): base(0), height(0) {}
Polygon(float b, float h): base(b), height(h) {}
virtual float area() {return -1;} //virtual method area
};
class Triangle:public Polygon {
public:
Triangle(): Polygon() {}
Triangle(float b, float h): Polygon(b,h) {}
float area() {return base*height/2;}
};
class Rectangle:public Polygon {
public:
Rectangle(): Polygon() {}
Rectangle(float b, float h): Polygon(b,h) {}
float area() {return base*height;}
};
int main() {
//Polymorphism
Triangle t1, t2(10,10);
Rectangle r1, r2(5,5);
Polygon *ptr[]={&t1,&t2,&r1,&r2};
cout<<ptr[0]->area()<<endl; //Output: 0
cout<<ptr[1]->area()<<endl; //Output: 50
cout<<ptr[2]->area()<<endl; //Output: 0
cout<<ptr[3]->area()<<endl; //Output: 25
cout<<ptr[0]->Polygon::area()<<endl; //Output: -1
}
【问题讨论】:
-
TL;DR 从你的问题标题看:这取决于。还有 static polymorhpism 不需要
virtual函数。 -
C++ 中唯一的覆盖是虚函数,但是有很多种多态性。
标签: c++ object inheritance polymorphism