当前位置:编程学习 > C#/ASP.NET >>

模板类中函数参数传值与传址问题! 请高手解决 谢谢

我做了一个通用线程类代码如下:
#pragma once
template <class Type> 
class BaseThread
{
private:
static   unsigned   int  __stdcall StaticRun(void *pParam);
public:

HANDLE run(Type paras);
virtual int threadExc(Type para)=0;
BaseThread(void);
~BaseThread(void);
};


template <class Type> 
BaseThread<Type>::BaseThread(void)
{
}
BaseThread<Type>::~BaseThread(void)
{
}

template <class Type> 
HANDLE BaseThread<Type>::run( Type para){
unsigned threadID;
ThreadInfo<Type> *mParas=new ThreadInfo<Type>;
mParas->para1=para;
mParas->para2=this;


HANDLE handle=(HANDLE)_beginthreadex(0, 0, StaticRun ,(void*)mParas, 0, &threadID);
return handle;
}

template <class Type> 
unsigned   int   BaseThread<Type>::StaticRun(void *pParam){
ThreadInfo<Type> *tParas=(ThreadInfo<Type>*)pParam;
BaseThread* baseThread=(BaseThread*)tParas->para2;
baseThread->threadExc(tParas->para1);
delete tParas;
_endthreadex(0);
return 0;
}
template <class Type> 

结构体如下:
struct ThreadInfo
{
T para1;
void *para2;

};

// testThread 继承BaseThread
template <class Type> 
class testThread :
public BaseThread <Type>
{

public:
testThread(void);
~testThread(void);

//int threadExc(const void *paras);
int threadExc(Type para);

};


template <class Type> 
testThread<Type> ::testThread()
{
}
template <class Type> 
testThread<Type>::~testThread(void)
{
}

template <class Type> 
int testThread<Type>::threadExc(Type para){
         char* value=para;
         cout<<value;
return 0;

}
-------------------
main(){
testThread<char*>test;   //testThread是BaseThread的子类,重载了threadExc方法
char *para="china";
HANDLE handle=test.run(para);
strcpy(para,"usa");
WaitForSingleObject(handle,INFINITE);
}
打印结果是:
usa

请问我如何打印出china;
模板参数自动变成对地址的操作.

如果参数改成传值.下面的代码是正确的.
testThread<int>test;   //testThread是BaseThread的子类,重载了threadExc方法
int i=12;
HANDLE handle=test.run(i);
i=99;

将上边的threadExc方法改为:

int testThread<Type>::threadExc(Type para){
         int value=para;
         cout<<value;
return 0;
}

那么打印出的是12;








}
--------------------编程问答-------------------- 你将参数换成string类型的吧
因为你之前的写法传递的只是一个指针,指针内容可以被改写的.
用string的话就是具体的传递了一个string对象过去,这个对象包含了你所需要的字符串,
补充:.NET技术 ,  VC.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,