2017-05-31 52 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; });