问题是由于以下错误,我无法编译:
ejercicio_4.cpp: In function ‘int main()’: *
ejercicio_4.cpp:32:49: error: cannot call member function ‘void Calculos::calcular_desvtipica(double)’ without object
P[2] = thread(Calculos::calcular_desvtipica(5.0), p3);
这是 Calculos.h
#ifndef CALCULOS_H
#define CALCULOS_H
#include <iostream>
#include <string>
#include <chrono>
#define N 100
using namespace std;
class Calculos {
public:
Calculos(double T[], int op);
Calculos();
void run();
void calcular_desvtipica(double media);
double *T;
int op;
double max, min, desvtipica, media;
};
#endif
Calculos.cpp
#include <iostream>
#include <string>
#include <chrono>
#include "Calculos.h"
using namespace std;
Calculos::Calculos(double T[], int op) {
this->T = T;
this->op = op;
};
Calculos::Calculos() { }
void Calculos::run() {
if(op == 1) { //calcular media
double suma = 0.0;
for(int i = 0; i < N; i++) {
suma = suma + T[i];
}
media = (double)(suma/N);
}
else if(op == 2) { //calcular maximo y minimo
double datoMax = T[0], datoMin = T[0];
for(int i = 1; i < N; i++) {
if(T[i] > max) max = T[i];
if(T[i] < min) min = T[i];
}
max = datoMax;
min = datoMin;
}
else { //op=3 calcular desviacion tipica
cout << "que cojones hago aqui" << endl;
}
};
void Calculos::calcular_desvtipica(double media) {
desvtipica = media/2.0;
};
这是的主要方法
#include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include "Calculos.h"
using namespace std;
int main() {
double T[N];
for(int i = 0 ; i < N; i++) {
T[i] = (double)rand();
}
thread P[3];
Calculos p1(T, 1),
p2(T, 2),
p3(T, 3);
P[0] = thread(&Calculos::run, p1);
P[1] = thread(&Calculos::run, p2),
P[0].join();
double m = p1.media;
P[2] = thread(Calculos::calcular_desvtipica(m), p3);
P[1].join();
P[2].join();
cout << "#datos: " << N << endl;
cout << "media: " << p1.media << endl;
cout << "min: " << p2.min << endl;
cout << "max: " << p2.max << endl;
cout << "sigma: " << p3.desvtipica << endl;
cout << "Fin\n";
return 0;
}
我尝试更改此行:
P[2] = thread(Calculos::calcular_desvtipica(m), p3);
至:
P[2] = thread(p3.calcular_desvtipica(m), p3);
但这不起作用。问题出在哪儿?
最佳答案
将P[2] = thread(Calculos::calcular_desvtipica(m), p3);
行替换为P[2] = thread(&Calculos::calcular_desvtipica, std::ref(p3), m);
顺便说一句,ref()可能也应该在其他std::thread构造函数中使用,因为您可能不想复制Calculos
对象。
关于c++ - 无效使用void表达式-C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33041919/