2017-05-31 19 views
1

晚上好! Java中有這樣的代碼,我需要在C++和QT中做同樣的事情,我如何替換Callable接口,我理解我需要使用單獨的線程或其他東西?C++和Qt中的可調用接口模擬器

public class Filter implements Callable<short[]> { 

protected short countOfCoefs; 
protected double[] coefsFilter; 
protected short[] inputSignal; 
protected short[] outputSignal; 
protected double gain; 

public Filter(final int lenghtOfInputSignal){ 
    gain = 1; 
    this.outputSignal = new short[lenghtOfInputSignal]; 
} 


public void settings(final double[] coefsFilter, final short countOfCoefs, final short[] inputSignal) { 
    this.inputSignal = inputSignal; 
    this.coefsFilter = coefsFilter; 
    this.countOfCoefs = countOfCoefs; 
    this.outputSignal = new short[inputSignal.length]; 
} 

private convolution[] svertka() { 
    int multiplication; 
    for(int i = 0; i < inputSignal.length - FilterInfo.COUNT_OF_COEFS; i++) { 
     for(int j = 0; j < this.countOfCoefs; j++) { 
      multiplication = (int) (this.inputSignal[i] * this.coefsFilter[j]); 
          this.outputSignal[i+j] += gain * (short)(multiplication); 
     } 
    } 
    return this.outputSignal; 
} 

public void setGain(float d) { 
    this.gain = d; 
} 

public double getGain() { 
    return this.gain; 
} 

public short[] getOutputSignal() { 
    return this.outputSignal; 
} 

public long getCountOfSamples() { 
    return this.inputSignal.length; 
} 

@Override 
public short[] call() throws Exception { 
    this.svertka(); 
    return this.outputSignal; 
} 

}

+1

您可以定義一個抽象類Callable,它只接受一個short []或std :: vector ,只定義析構函數。無需線程。 –

+1

也不需要抽象類。 C++不需要這些。最好不要嘗試在C++中編寫Java代碼。使用每種語言來發揮其優勢。 – juanchopanza

+0

@juanchopanza - 通過抽象類,我指的是一個包含至少一個純虛擬方法的類。 C++的這一特性在Java的第一個公開發布之前預先計劃好了。 Stroustrup在他的1994年出版的「C++的設計和發展」一書中進行了介紹。 Java 1.0於1995年發佈。抽象類的概念不是特定於語言的。 Callable.call()方法必須是虛擬的。據我所知,使其成爲純粹的虛擬成本沒有任何額外的成本,並消除了意外傳入非子類Callable的可能性。在C++中爲此目的使用抽象類是合適的。 –

回答

0

有多種方法和選擇正確的取決於你想要達到的目標:

1)如果你想多線程,你可以讀到:

1a)Qt支持線程,您可以從this文檔頁面

1b)std::packaged_taskC++ thread library注意:這需要一個C++ 11編譯器

2)如果你只需要一個接口,可以實現在C++這樣的:

class ICallable 
{ 
    public: 
     virtual ~ICallable() {} 
     virtual void Call(std::vector<short> shorts) = 0; 
}; 

3)如果你只是需要一個對象,其行爲就像一個功能,您可以創建一個仿函數或使用lambda(如果你有C++ 11的支持):

class myFunctorClass 
{ 
    public: 
     myFunctorClass() {} 
     int operator() (int x) { return x * x; } 
    private: 
     //you can have member variables, initialize them in constructor 
}; 

LAMBDA例如定製的std ::排序

std::vector<int> v; 
//populate v 
std::sort(v.begin(), v.end(), [](int l, int r) { return l > r; });