【发布时间】:2020-12-15 12:36:16
【问题描述】:
首先,有一个名为Shape的父类,它有两个构造函数,一个有一个参数,另一个有两个参数。有两个类从“Shape”类继承属性。它们是矩形和圆形。
我用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'
【问题讨论】:
-
这能回答你的问题吗? Undefined reference to vtable
-
getArea()不是纯虚拟的,也不是定义的。 -
不要尝试直接将 java 翻译成 c++,尽管它们看起来很相似,但它们是非常不同的语言。有明显的区别(例如 C++ 没有
abstract关键字)和更细微的区别,比如初始化成员应该在成员初始化列表中而不是在构造函数的主体中完成。清单上还有很多... -
@stevesiddu 不是这样的
标签: java c++ oop inheritance abstraction