最近在使用COM的字符串时,觉得_bstr_t的自动类型转换非常有意思,故特来研究。
下面是_bstr_t的一些用法:
将char*/WCHAR*值赋给_bstr_t
m_rst->GetFields()->GetItem(nCol)->Value = (_bstr_t)sValue;
从_bstr_t返回char*/WCHAR*值
strcpy(sValue, (char*)(_bstr_t)vValue);
wcscpy(sValue, (WCHAR*)(_bstr_t)vValue);
仔细分析这 m_rst->GetFields()->GetItem(nCol)->Value = (_bstr_t)sValue;
它含有两个用法
(_bstr_t)sValue 表示建立临时类_bstr_t对象,这将引起关于_bstr_t类的_bstr_t(char*)构造函数被调用
vValue = (_bstr_t) 表示vValue的 operator =(_bstr_t)将被调用
我的例子
class TestAA
{
int num;
public:
TestAA(int a)
{
num = a;
}
TestAA(long a)
{
num = (int)a;
}
TestAA &operator = (int a) //赋值重载 TestAA AA(10); AA = (int)10;
{
num = a;
return *this;
}
TestAA &operator = (long a)
{
num = (int)a;
return *this;
}
operator long () //定义TestAA类的强制类型转换,使用用法是TestAA AA(10); (long)AA;
{
return (long)num;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
long a = 10;
TestAA aa(a); //调用TestAA(long a)构造
a = 20;
aa = a; //调用TestAA &operator = (long a)
long lll = (long)aa; //调用 operator long () 强制类型转换,并返回值给 lll
(TestAA)(long)10; //调用TestAA(long a)构造 临时对象
(TestAA)(long)aa; //先调用 operator long () 强制类型转换,再将返回值调用调用TestAA(long a)构造,建立临时对象
return 0;
}
后面的情况,我从网上摘了一个例子,和_bstr_t很相似,这里表示感谢
#include < stdio.h >
#include < string >
class MyData
{
public :
MyData( const int nValue, const char * pszValue)
{
m_nValue = nValue;
m_strValue = pszValue;
}
void Set( const int nValue, const char * pszValue)
{
m_nValue = nValue;
m_strValue = pszValue;
}
// 重载类型转换操作
operator int () // operator int&() 也可以
{
return m_nValue;
}
operator const char * ()
{
return m_strValue.c_str();
}
operator char * ()
{
return const_cast < char *> (m_strValue.c_str());
}
protected :
int m_nValue;
std:: string m_strValue;
} ;
void PrintInt( int n)
{
printf( " %d/n " , n);
}
void PrintString( const char * psz)
{
if (psz != NULL)
printf( " %s/n " , psz);
}
void Print( int n)
{
PrintInt(n);
}
void Print( char * p)
{
PrintString(p);
}
void main( void )
{
MyData myData( 11 , " aa " );
PrintInt(myData); //这个将进行隐式类型转换,调用( int )myData
PrintString(myData);
// Print(myData); // compile error ,因为有两个print,编译器不知道进行哪个隐式类型转换
Print(( int )(myData)); // 调用Print(int n)
Print(( char * )(myData)); // 调用Print(char * p)
}