C++类型转换重载研究(一)

最近在使用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)
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值