分析测试百科网

搜索

喜欢作者

微信支付微信支付
×

C++之类型转换函数(五)

2020.9.28
头像

王辉

致力于为分析测试行业奉献终身

输出结果:

root@txp-virtual-machine:/home/txp# g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:21:8: error: no match for ‘operator=’ (operand types are ‘Test’ and ‘int’)
     t =6;
       ^
test.cpp:21:8: note: candidate is:
test.cpp:4:7: note: Test& Test::operator=(const Test&)
class Test{
      ^
test.cpp:4:7: note:   no known conversion for argument 1 from ‘int’ to ‘const Test&’

注解:这里显示不能这样转换

代码实践二(进行显示转换):

#include <iostream>
#include <string>
class Test{
public:
   Test()
   {
   }
  explicit Test(int i)
   {
   }
};
int main()

    Test t;
    t =static_cast<Test>(6);
    return 0;

输出结果(编译通过):

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

4、小结:

转换构造函数只有一个参数

转换构造函数的参数类型是其它类型

转换构造函数在类型转换时被调用

隐式类型转换是工程中bug的重要来源

explicit关键字用于杜绝隐式类型转换

二、类型转换函数:

1、类类型转换普通类型:

在我们上面通过代码测试发现不行,那么是真的不行吗,事实是可以进行转换的,不过要用到我们现在c++里面的类型转换函数(它用于将类对象转换为其它类型),类型转换的语法如下:

operator Type()

   Type ret;
   
   return ret;

代码实践:

#include <iostream>
#include <string>
class Test{
public:
   Test()
   {
   }
  operator int()
  {
   }
};
int main()

    Test t;
    int i =t;
    return 0;

输出结果(编译没有报错):

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

注:

与转换构造函数具有同等的地位

使得编译器有能力将对象转化为其它类型

编译器能够隐式的使用类型转换函数


互联网
文章推荐