1

Java 不支持抽象类的多重继承,但我试图在 C++ 中做与此等效的操作:

//this is Java-style pseudocode
public abstract class Rectangle{
    public abstract double getHeight();
    public abstract double getWidth();
    public double getHeight(){
        return getWidth()*getHeight();
    }
}

public abstract class Container{
    public abstract void printTypes();
    public abstract void printEachElement();
    public void printContainerStuff(){
        System.out.print("Has the types: ");
        printTypes();
        System.out.print("List of elements: ");
        printEachElement();
    }
}

public abstract class Array extends Rectangle, Container{ //this can't be done in Java, but what about C++?

}

C++ 中是否有等效的 Java 抽象类可以做到这一点?

4

4 回答 4

3

要在 C++ 中使类抽象,至少一个成员函数必须是纯虚函数:

class X
{
public:
    virtual void f() = 0;
};

如前所述,在 C++ 中允许多重继承:

class Rectangle
{
public:
    virtual double getHeight() = 0;
    virtual double getWidth() = 0;
    double getHeight(){
        return getWidth()*getHeight();
    }
};

class Container
{
public:
    virtual void printTypes() = 0;
    virtual void printEachElement() = 0;
};

class Array: public Rectangle, public Container
{
    // If the pure virtual member functions in the base classes
    // are not implemented then this class is also abstract.
};
于 2012-06-15T19:54:27.430 回答
2

我认为您正在寻找 Java 接口。

public abstract class Rectangle{
    public abstract double getHeight();
    public abstract double getWidth();
    public double getHeight(){
        return getWidth()*getHeight();
    }
}

public interface Container {
    public void printTypes();
    public void printEachElement();
}

public abstract class Array extends Rectangle implements Container {
}

在 C++ 中,您可以拥有多重继承。您还可以使用带有纯虚拟方法的 Java 接口之类的东西。

class Container {
    public:
        virtual void printTypes() = 0;
        virtual void printEachElement() = 0;
}
于 2012-06-15T19:52:03.467 回答
2

C++ 允许多重继承。所以这在 C++ 中是允许的。

而在 C++ 中相当于 Java 的抽象类是一个至少有一个 virtual成员函数的类。

因此,C++ 中 Java 代码的等价物将是:

class Rectangle
{
  public:
    virtual double getHeight() = 0;
    virtual double getWidth() = 0;
    double getHeight(){
        return getWidth()*getHeight();
    }
};

class Container(){
  public:
    virtual void printTypes() = 0;
    virtual void printEachElement() =0;
};
于 2012-06-15T19:52:08.460 回答
-1

如果你想要继承行为。(代码是Java,你可以在c++中尝试这样的事情)

abstract class Rectangle{

    public abstract double getHeight();
    public abstract double getWidth();
    public double getHeight(){
        return getWidth()*getHeight();
    }
}

abstract class Container extends Rectangle{
    public abstract void printTypes();
    public abstract void printEachElement();
}

abstract class Array extends Container{ 

}
于 2012-06-15T19:56:06.863 回答