在Java中,我们可以声明一个接口(interface)变量而无需实例化。这可以帮助我们处理一些抽象的概念。在下面的 Java 示例中,我定义了一个接口(interface) UShape
和两个 UShape
类,Rectangle
和 Triangle
。在测试类存储桶中,我能够定义一个名为 myshape
的私有(private)接口(interface)变量,并使用该变量执行操作。
interface UShape {
void setwidth(int i);
void setheight(int i);
int getarea();
}
class Rectangle implements UShape{
private int w, h;
@Override
public void setwidth(int i) {
this.w = i;
}
@Override
public void setheight(int i) {
this.h = i;
}
@Override
public int getarea() {
return this.w * this.h;
}
}
class Triangle implements UShape{
private int w, h;
@Override
public void setwidth(int i) {
this.w = i;
}
@Override
public void setheight(int i) {
this.h = i;
}
@Override
public int getarea() {
return this.w * this.h / 2;
}
}
class bucket{
private UShape myshape;
//do something with myshape
public void defineShape(int i){
if (i == 1){
myshape = new Rectangle();
myshape.setwidth(5);
myshape.setheight(5);
}
}
public void printArea(){
System.out.println(myshape.getarea());
}
}
public class TestShape {
public static void main(String[] args){
bucket b = new bucket();
b.defineShape(1);
b.printArea();
}
}
我现在的问题是,在C++中,我们如何实现这个程序?我查了一下,发现C++中的抽象类不能用来声明UShape myshape
这样的变量。我们是否可以使用其他方法来实现带有接口(interface)变量的 bucket 之类的类?
最佳答案
也许我误解了你的问题,但你没有理由不能声明抽象类类型的私有(private)成员。以下内容应该类似于您的 Java 示例:
class UShape {
public:
virtual void setWidth (int w) =0;
virtual void setHeight (int h) =0;
virtual int getArea() =0;
virtual ~UShape() =0;
};
class Rectangle: public UShape {
private:
int width;
int height;
public:
void setWidth (int w) { this.width = w; }
void setHeight (int h) { this.height = h; }
int getArea (void) { return (width * height); }
};
class Triangle: public UShape {
private:
int width;
int height;
public:
void setWidth (int w) { this.width = w; }
void setHeight (int h) { this.height = h; }
int getArea (void) { return (width * height) / 2; }
};
class bucket{
private:
std::unique_ptr<UShape> myshape;
public:
//do something with myshape
void defineShape(int i){
if (i == 1){
myshape = std::make_unique<Rectangle>();
myshape->setWidth(5);
myshape->setHeight(5);
}
}
void printArea(){
cout << myshape ? myshape->getArea() : 0;
}
}
int main () {
bucket b();
b.defineShape(1);
b.printArea();
}
关于java - 在 C++ 中,我可以像在 Java 中一样拥有接口(interface)变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36273379/