C ++中抽象类的多重继承

时间:2012-06-15 19:50:34

标签: java c++ class inheritance abstract

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 个答案:

答案 0 :(得分: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.
};

答案 1 :(得分: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;
}

答案 2 :(得分: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;
};

答案 3 :(得分:-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{ 

}