gpt4 book ai didi

c++ - 不能取值对象 - C++

转载 作者:太空狗 更新时间:2023-10-29 23:50:11 25 4
gpt4 key购买 nike

我在获取“p1.media”的值时遇到问题。值是 media: 6.91026e-310 并且必须像 1000、5000...。我尝试了太多的解决方案,但任何人都有效。这是代码:

Code of Calculos.h

#ifndef CALCULOS_H
#define CALCULOS_H
//includes
#define N 100
using namespace std;

class Calculos {
public:
Calculos(double T[], int op);
Calculos(double T[], int op, double media);
Calculos(); //constructor por defecto
void run();

int op;
double desvtipica, media, *T;
};
#endif

Code of Calculos.cpp

//includes
#include "Calculos.h"
using namespace std;

Calculos::Calculos(double T[], int op) {
this->T = T;
this->op = op;
desvtipica = 0.0;
};

Calculos::Calculos() {
}
Calculos::Calculos(double T[], int op, double media) {
this->T = T;
this->op = op;
this->media=media;

};
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 { //op=3 calcular desviacion tipica
desvtipica = 3.0; //partially
}
};

Code of Ejercicio.cpp

//includes
#include "Calculos.h"
#include <iostream>
#include <cstdlib>
#include <thread>

using namespace std;

double fRand(double fMin, double fMax)
{
double f = (double)rand() / RAND_MAX;
return fMin + f * (fMax - fMin);
};

int main() {
cout << "#datos: " << N << endl;
double T[N];
for(int i = 0 ; i < N; i++) {
T[i] = fRand(1.0, 1000.0);
}

thread P[2];

Calculos p1(T, 1);
P[0] = thread(&Calculos::run, p1);
P[0].join();
double m = p1.media; // Here is the problem. p1.media return bad values
cout << "media: " << m << endl;
Calculos p3(T, 3, m);
P[1] = thread(&Calculos::run, p3);
P[1].join();

cout << "Fin\n";
return 0;
}

最佳答案

将参数传递给 thread 构造函数的方式存在问题。

改变:

   P[0] = thread(&Calculos::run, p1); // creates a copy of p1

到:

   P[0] = thread(&Calculos::run, std::ref(p1)); // pass p1 by reference

现在的输出是:

#datos: 100
media: 547.278
Fin

Notes

The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g. with std::ref or std::cref).

Source: http://en.cppreference.com/w/cpp/thread/thread/thread (emphasis mine)


在你的代码中,p1.media0 因为你没有对它做任何事情。您已经使用了 p1 的临时拷贝。

关于c++ - 不能取值对象 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33067306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com