您好,我在運行此腳本時出錯。它使用多線程,並在類中有數組。例如,我試圖設置數組,並使用foo1
和foo
做一個while (gg[50] != 40) do xxxxxx
。從C++中的類訪問數組內容時出錯
我有一個cout
來驗證數組已設置,但它返回垃圾,但當我問在主,它返回正確。有沒有解決這個問題?或者有沒有更好的方法在Windows中做到這一點?
#include "stdafx.h"
#include <thread>
#include <iostream>
#include <stdio.h> /* printf */
#include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */
using namespace std;
class bar {
public:
void setarray(int r, double y){
gg[r] = y;
}
void foo() {
int y = 0;
cout << gg[50] << "gg2" << endl;
std::cout << "hello from member function2" << std::endl;
while (gg[50] != 40){
y++;
}
cout << y << " y2" << endl;
}
void foo1() {
int y = 0;
std::cout << "hello from member functiondddw1" << std::endl;
cout << gg[50]<< "gg1"<<endl;
std::thread(&bar::foo, bar()).detach();
while (gg[50] != 40){
y++;
}
cout << y << " y1" << endl;
}
double getarray(int g){
double ek = gg[g];
return ek;
}
private:
double gg[80];
};
int main()
{
bar jj;
int u=0;
cout << "which array" << endl;
cin >> u;
double dd=0;
cout << "which number" << endl;
cin >> dd;
jj.setarray(u, dd);
if(jj.getarray(u) == 3){
clock_t tt;
tt = clock();
std::thread(&bar::foo1, bar()).detach();
tt = clock() - tt;
printf("It took me %d clicks (%f seconds).\n", tt, ((float)tt)/ CLOCKS_PER_SEC);
cout << "done" << endl;
}
cout << jj.getarray(50);
u=0;
cout << "which array" << endl;
cin >> u;
dd=0;
cout << "which number" << endl;
cin >> dd;
jj.setarray(u, dd);
cin.get();
return 0;
}
感謝您的回答我已經嘗試過您的答案,但仍然沒有..我在調用任何線程之前分配gg [50],因此加入/分離不應該發揮作用AFAIK – user3370016