发布时间:2020-09-28 23:10 原文链接: C++之类型转换函数(六)

2、类类型之间的转换:

这个问题也是之前我们上面简单的测试,不能进行类类型之间的转换;现在我们学习了类型转换函数,是可以进行转换的:

代码版本一:

#include <iostream>
#include <string>
using namespace std;
class Test;
class Value

public:
   Value()
   {
   }
   explicit Value(Test& t)
   {
   }
};
class Test

   int mValue;
public:
   Test(int i = 0)
   {
       mValue = i;
   }
   int value()
   {
       return mValue;
   }
   operator Value()
   {
       Value ret;
       cout << "operator Value()" << endl;
       return ret;
   }
工程上通过以下方式;
 Value toValue()
 {
     Value ret;
     
     return ret;
 
 }
};
int main()
{  
   Test t(100);
   Value v = t;
   
   return 0;

输出结果(编译通过):

root@txp-virtual-machine:/home/txp# g++ test.cpp
root@txp-virtual-machine:/home/txp#

注意:这里还有一种让编译器犯难的转换写法;我们上面这样写是用explicit关键字屏蔽了Value类里面的隐式转换,所以不会犯难,下面是犯难的代码示例:

#include <iostream>
#include <string>
using namespace std;
class Test;
class Value

public:
   Value()
   {
   }
    Value(Test& t)
   {
   }
};
class Test

   int mValue;
public:
   Test(int i = 0)
   {
       mValue = i;
   }
   int value()
   {
       return mValue;
   }
   operator Value()
   {
       Value ret;
       cout << "operator Value()" << endl;
       return ret;
   }
};
int main()
{  
   Test t(100);
   Value v = t;
   
   return 0;