gpt4 book ai didi

java - 如何通过使用C++中的构造函数获取父类的变量来在子类中实现抽象类方法

转载 作者:行者123 更新时间:2023-12-02 09:47:54 25 4
gpt4 key购买 nike

首先,有一个名为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(){};

关于java - 如何通过使用C++中的构造函数获取父类的变量来在子类中实现抽象类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63602229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com