我想創建一個實現一些自己的方法在Java中(但語言不會允許這樣做,如下圖所示)的接口的接口:創建實現一些自己的方法
//Java-style pseudo-code
public interface Square {
//Implement a method in the interface itself
public int getSize(){//this can't be done in Java; can it be done in C++?
//inherited by every class that implements getWidth()
//and getHeight()
return getWidth()*getHeight();
}
public int getHeight();
public int getWidth();
}
//again, this is Java-style psuedocode
public class Square1 implements Square{
//getSize should return this.getWidth()*this.getHeight(), as implemented below
public int getHeight(){
//method body goes here
}
public int getWidth{
//method body goes here
}
}
是否有可能在C++中創建等價的接口來實現一些自己的方法?
是否有任何理由你不能只擴展類而不是實現它? –
改爲創建抽象類。 –