【发布时间】:2016-08-16 01:38:28
【问题描述】:
我不明白多态性和继承之间的区别......他们在文学上做同样的事情......
多态的简单例子:
class shape {
public:
void setValues(int height_, int width_) {
height = height_, width = width_;
}
protected:
int height, width;
private:
};
class rectangle :public shape, public ThreeDView{
public:
int area() {
return(shape::height*shape::width);
}
float threeDArea() {
return(((shape::height*shape::width)/2)*(std::cos(Z_LENGTH)));
}
};
class ThreeDView{
public:
void setZLength(int value) {
Z_LENGTH = value;
}
int setCompact(bool ans) {
compact = ans;
}
float getZLength() {
return Z_LENGTH;
}
bool getCOMPACT() {
return compact;
}
protected:
float Z_LENGTH;
bool compact;
private:
unsigned char ZCHAR = 'Z';
};
class triangle :public shape {
public:
int area() {
return((shape::height * shape::width) / 2);
}
};
int main(){
rectangle rect2;
triangle trng2;
shape *poly = &rect2;
shape *poly2 = &trng2;
poly->setValues(2,3);
poly2->setValues(5,4);
std::cout << "AREA : " << trng1.area() << "AREA RECT : \n" <<rect1.area() << std::endl;
}
上面的例子翻译成继承:
class shape {
public:
void setValues(int height_, int width_) {
height = height_, width = width_;
}
protected:
int height, width;
private:
};
class rectangle :public shape, public ThreeDView{
public:
int area() {
return(shape::height*shape::width);
}
float threeDArea() {
return(((shape::height*shape::width)/2)*(std::cos(Z_LENGTH)));
}
};
class triangle :public shape {
public:
int area() {
return((shape::height * shape::width) / 2);
}
};
int main(){
rectangle rect2;
triangle trng2;
rect2.setValues(2,3);
trng2.setValues(5,4);
std::cout << "AREA : " << trng1.area() << "AREA RECT : \n" <<rect1.area() << std::endl;
}
请告诉我差异。老实说,我什至没有看到多态性的使用!感谢您的帮助!
【问题讨论】:
-
多态和继承是两个正交的概念,它们之间根本没有相似之处,只有区别。
-
另外,你的例子有缺陷。第一个根本不使用多态性。
-
什么是
ThreeDView?除非它有一个虚函数,否则你没有任何 polymorphic 类型。这可能会造成混乱。 -
不,它没有。现在您已经告诉我们
ThreeDView,您没有任何多态类型。谷歌这个词;它应该对你有帮助。 -
继承可以用作实现多态行为的一种手段。但是,还有其他的,例如模板。
标签: c++ inheritance polymorphism