首先,有一个名为Shape的父类,它有两个构造函数,一个带有一个参数,另一个带有两个参数。有两个类从“ Shape”类继承属性。它们是Rectangle和Circle。
我使用Java进行了尝试,得到了想要的东西。
这是java实现。
package javaapplication6;
import java.io.*;
abstract class Shape{
protected int radius,length,width;
public Shape(int n){
radius=n;
}
public Shape(int x,int y){
length=x;
width=y;
}
abstract public void getArea();
}
class Rectangle extends Shape{
public Rectangle(int x,int y){
super(x,y);
}
public void getData(){
System.out.println(length+" "+width);
}
public void getArea(){
System.out.println("Area of Reactangle is : "+width*length);
}
}
class Circle extends Shape{
public Circle(int x){
super(x);
}
public void getData(){
System.out.println(radius);
}
public void getArea(){
System.out.println("Area of Reactangle is : "+2*radius*3.14);
}
}
public class JavaApplication6 {
public static void main(String[] args) {
Rectangle r=new Rectangle(3,4);
r.getData();
r.getArea();
System.out.println();
Circle c=new Circle(3);
c.getData();
c.getArea();
}
}
我想要确切的东西在C ++中实现。
我尝试如下
#include<bits/stdc++.h>
using namespace std;
class Shape{
public:
int r,x,y;
Shape(int rad){
r=rad;
}
Shape(int height,int width){
x=height;
y=width;
}
void getClass(){
cout<<"Ur in class shape"<<endl;
}
virtual void getArea();
};
class Rectangle : public Shape{
public:
Rectangle(int x,int y):Shape(x,y){}
void getArea(){
cout<< "Area of rectangle : "<<x * y<<endl;
}
void getClass(){
cout<<"Ur in class Rectangle"<<endl;
}
};
class Circle : public Shape{
public:
Circle(int r):Shape(r){}
vooid getArea(){
cout<< "Area of Circle : "<<2* 3.14 * r<<endl;
}
void getClass(){
cout<<"Ur in class Circle"<<endl;
}
};
int main(){
Circle c(5);
c.getClass();
c.getArea();
Rectangle r(3,4);
r.getClass();
r.getArea();
}
但是我出错了。
abstract.cpp:(.rdata$.refptr._ZTV5Shape[.refptr._ZTV5Shape]+0x0): undefined reference to `vtable for Shape'
您会收到错误消息,因为没有的定义Shape::getArea
,也没有将其声明为纯虚拟的:
virtual void getArea();
要使其成为纯虚拟的,您需要:
virtual void getArea() = 0;
另外,您应该提供一个虚拟的析构函数。什么时候需要它,什么时候不超出这个问题的范围。最简单的就是提供它:
virtual ~Shape(){};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句