C++ 如何在c+中的两个函数中传递对象的相同实例+;
我需要在两个函数(主函数和线程函数)中发送同一个类的对象实例 节目是这样的C++ 如何在c+中的两个函数中传递对象的相同实例+;,c++,multithreading,class,object,C++,Multithreading,Class,Object,我需要在两个函数(主函数和线程函数)中发送同一个类的对象实例 节目是这样的 Class ABC { }obj(32); void F1() { obj.test; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { obj.test1; _beginthread(F1,0,(void*)number); } Class
Class ABC
{
}obj(32);
void F1()
{
obj.test;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
obj.test1;
_beginthread(F1,0,(void*)number);
}
Class ABC
{
public:
DWORD *IdG;
ABC(int number)
{
IdG = new DWORD[number];
}
}
void F1(thestruct* st)
在上面的示例中,我创建了类ABC并将其对象声明为obj(32)。我在Main函数中调用这个对象。在Main函数中,使用线程调用函数“F1”,在函数“F1”中调用相同的对象“obj”
如上图所示,创建ABC类的对象时,代码运行良好。我的问题是要从文件中读取在对象('32')中传递的值
如果在主函数和函数“F1”中分别读取文件和创建对象,则不会执行函数“F1”
如何使用从文件中获取的对象中传递的值为主函数和函数“F1”创建相同的对象实例
用于从文件中读取的代码是
FILE *fileread;
int character;
fileread=fopen("C:/file.txt", "r");
if (fileread==NULL)
{
return 1; // exit with failure
}
int n,number;
while((fscanf(fileread, "%d",&n))==1)
{
number=n;
}
fclose(fileread);
现在,创建的对象应该类似于obj(number)
ABC obj(number)
的同一实例将在主函数和函数“F1”中定义
//////////////////更新的//////////////////////////////////////////////
我的班级是这样的
Class ABC
{
}obj(32);
void F1()
{
obj.test;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
obj.test1;
_beginthread(F1,0,(void*)number);
}
Class ABC
{
public:
DWORD *IdG;
ABC(int number)
{
IdG = new DWORD[number];
}
}
void F1(thestruct* st)
然后我定义了typedef,以便在beginthread中发送两个参数
typedef struct ST{
int num;
CMinimalServer* srv1;
}thestruct;
我的函数是这样的
Class ABC
{
}obj(32);
void F1()
{
obj.test;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
obj.test1;
_beginthread(F1,0,(void*)number);
}
Class ABC
{
public:
DWORD *IdG;
ABC(int number)
{
IdG = new DWORD[number];
}
}
void F1(thestruct* st)
主要功能是
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
thestruct st;
st.num =32;
st.srv1; // problem is here how to specify class constructor as srv1(32).
//beginthread part is modified as below
_beginthread((void(*)(void*))ModbusReadWrite,0,(void*)&st);
我需要将类对象创建为abcsrv1(32)您可以为结构定义构造函数:
typedef struct ST {
int num;
CMinimalServer* srv1;
explicit ST(int num);
} thestruct;
ST::ST(int _num) : num(_num), srv1(new ABC(_num))
{
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
thestruct st(32);
// here:
// st.num == 32
// st.srv1 points to ABC(32)
将函数参数
F1(ABC*obj)
作为\u beginthread
中的参数传递给它作为\u beginthread(F1,0,(void*)obj)代码>。使用(Win OS)低级别线程功能对您来说重要吗?否则,我建议使用et.al.@Etherealone谢谢你的评论,我不能将obj作为void发送,所以我创建了struct,并更新了上面文章中更改的madein。你能帮帮我吗?@πάνταῥεῖ 我必须使用低级线程。我已经更新了帖子。你能看看里面吗it@Jenifer“我无法将obj作为void发送”您必须将地址作为void*
传递给线程函数,并将其转换回线程函数中的对象地址类型。感谢您的回复。当我们为结构定义构造函数时,如何在main函数中定义结构的对象。之前我们定义为“struct st;st.num=32;st.srv1”,我已经稍微展开了答案。还有更多细节吗?