在C++中有一个特殊的运算符重载方法--类型转换运算符重载,形如:operator type();    type可以是基本类型,也可是类类型。

 

/*
* type_conv.cpp
*
* Created on: 2009-8-14
* Author: kwarph
* Mail: kwarph@gmail.com
*/
#include 
<iostream>

using namespace std;

class Horse
{
public:
    Horse() :weight(
0), speed(0), teeth(0
      {
      }
      
      Horse(
const int& w, const int& s, const int& t = 0) : weight(w), speed(s), teeth(t) 
      {
      }
      
      
void neigh() const 
      {
          cout 
<< "吾本千里马也! " << "体重: " << weight << ", 奔跑时速: " << speed << endl;
      }
      
      
// 其它成员函数略 ...
      
private:
    
int weight;
    
int speed;
    
int teeth;
    
    
// 其它成员变量略 ...
    
};

class Deer 
{
public:
    Deer():weight(
0), speed(0
      {
      }
      
      Deer(
const int& w, const int& s) : weight(w), speed(s) 
      {
      }
      
      
operator Horse() const //此处
      {
          
return Horse(weight, speed);
      }
      
      
operator int() const //此处
      {
          
return weight + speed;
      }
      
      
void speak() const 
      {
          cout 
<< "我是如假包换的鹿" << endl;
      }
      
      
// 其它成员函数略 ...
      
private:
    
int weight;
    
int speed;
    
    
// 其它成员变量略 ...
    
};

void listen(const Horse& h) 
{
    h.neigh();
}

int main() 
{
    Deer d(
4068); // 这是一头鹿,40kg体重,时速68公里的奔跑速度
    d.speak(); // 不信听他说的:我是如假包换的鹿
    
    listen(d); 
// 可是在这里,鹿却变成了马,听他的嘶鸣:
    
// 吾本千里马也! 体重: 40, 奔跑时速: 68
    
    
// 更糟糕的是,一头鹿还可以变成int,不然他怎么会与int为伍?整个一部《哈利波特》
    int n = 12 + d; // 12 + 40 + 68 = 120
    cout << n << endl; // 120
}

另一例:

 

class CDemo
{
public:    
    CDemo(
int x,int y)
    {
        
this->_x = x;
        
this->_y = y;
    }
    
operator int()
    {    
// 运算符重载
        return _x;
    }  
private:
    
int _x;
    
int _y;
};
int _tmain(int argc, _TCHAR* argv[])
{
    CDemo demo(
10,30);
    cout
<<demo<<endl;
    
return 0;
}

 

posted on 2009-11-23 10:20  maxweii  阅读(312)  评论(0)    收藏  举报