当前位置:首页 > 公众号精选 > C语言与CPP编程
[导读]一、转换构造函数的学习: 1、回忆数据类型转换: 在平时写代码的时候,最怕的就是那种隐式数据类型转换了,一不小心,软件就bug不断;而显式数据类型(一般是程序自己去强制类型转换,这个是我们能够明显的识别和掌控的)。为此我们这里总结了一副隐式类型转


一、转换构造函数的学习:

1、回忆数据类型转换:

在平时写代码的时候,最怕的就是那种隐式数据类型转换了,一不小心,软件就bug不断;而显式数据类型(一般是程序自己去强制类型转换,这个是我们能够明显的识别和掌控的)。下面,我们来几个隐式转换的例子:

代码版本一:

#include #include int main()
{
     short s ='a';
     unsigned int ui = 100;
     int i = -200;
     double d = i;

     std::cout<<"d =" << d <"ui= "<if((ui+i)>0)
     {
          std::cout<<"Postive"<else {
        std::cout<<"Negative"<return 0;
}

输出结果:

root@txp-virtual-machine:/home/txp# ./a.out d =-200
ui= 100
Postive

注解:这里我们明显发现(-200+100)还是大于0,这显然不符合正常人的思维了;所以我们仔细分析一下,发现这里肯定是进行了隐式转换了,为此我们再加一条语句看看(ui+i)的值到底是多少:

代码版本二:

#include #include int main()
{
     short s ='a';
     unsigned int ui = 100;
     int i = -200;
     double d = i;

     std::cout<<"d =" << d <"ui= "<if((ui+i)>0)
     {
        std::cout<<"(ui+i) = "<"Postive"<else {
        std::cout<<"Negative"<return 0;
}

输出结果:

root@txp-virtual-machine:/home/txp# ./a.out d =-200
ui= 100
(ui+i) = 4294967196
Postive

注解:通过打印(ui+i)的值我们发现,i原本是int数据类型,这里隐式转换成无符号的数据类型了

为了让大家更加理解隐式的转换,我们下面再来一个例子:

代码版本三:

#include #include int main()
{
     short s ='a';
     unsigned int ui = 100;
     int i = -200;
     double d = i;

     std::cout<<"d =" << d <"ui= "<if((ui+i)>0)
     {
        std::cout<<"(ui+i) = "<"Postive"<else {
        std::cout<<"Negative"<"sizeof(s+'b') = "<'b')<return 0;
}

输出结果:

root@txp-virtual-machine:/home/txp# g++ test.cpp root@txp-virtual-machine:/home/txp# ./a.out d =-200
ui= 100
(ui+i) = 4294967196
Postive
sizeof(s+'b') = 4

注解:这里我们发现sizeof出来的内存大小是4个字节大小;其实这里编译器把short和char类型的都转换int类型了,所以最终两个int数据相加,所占的内存大小就是int类型了。

所以咋们平时在写代码的时候,脑袋里面要有这种写代码谨慎的思维,防止出现这种隐式转换的情况出现,养成写代码的好习惯

2、普通类型与类类型之间能否进行类型转换,类类型之间又是否能够类型转换呢?

为了说明这些问题,咋们通过实际的代码测试来看看啥情况:

代码:普通类型转换成类类型

#include #include class Test{

public: Test()
    {

    }
    Test(int i)
    {

    }
};

int main()
{
     Test t;

     t =6; 从 C 语言角度,这里将 5 强制类型转换到 Test 类型,只不过编译器 在这里做了隐式类型转换 return 0;
}

输出结果(显示可以编译通过)

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

代码类类型转换为普通类型

#include #include class Test{

public: Test()
    {

    }
    Test(int i)
    {

    }
};

int main()
{
     Test t;

     int i = t; return 0;
}

输出结果(没有编译通过)

root@txp-virtual-machine:/home/txp# g++ test.cpp test.cpp: In function ‘int main()’:
test.cpp:21:14: error: cannot convert ‘Test’ to ‘int’ in initialization
      int i = t;
              ^

代码类类型与类类型之间的转换:

#include #include class Value{

};


class Test{

public: Test()
    {

    }
    Test(int i)
    {

    }
};

int main()
{
     Test t;
     Value i;

     t=i; return 0;
}

输出结果(暂时还是不行,编译不通过):

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

说明:上面的例子,我们只是简单的按照实际角度出发,发现确实有写转换行不通。那么真理到底是怎样的?我们接着往下看

3、转换构造函数出厂:

我们前面学习过构造函数,构造函数它可以定义不同类型的参数;但是我们今天这里所说的转换构造函数的定义时这样的:

  • 有且仅有一个参数

  • 参数是基本类型

  • 参数是其它类型

接着我们对上面的普通数据类型转换类类型的代码进行分析:

#include #include class Test{

public: Test()
    {

    }
    Test(int i)
    {

    }
};

int main()
{
     Test t;

     t =6; //从 C 语言角度,这里将 5 强制类型转换到 Test 类型,只不过编译器 在这里做了隐式类型转换 return 0;
}

分析:

上面的Test(int i )就是一个转换构造函数,所以我们上面的这句隐式转换语句:

t =6

这里其实发生了我们刚才说的利用了转换构造函数,把6转换成Test(6),而这样写就会产生一临时对象,所以就可以进行赋值了;但是在现在的技术发展中,肯定是不希望出现这种要人去防止这隐式转换,所以在c++中有了新技术来防止出现隐式转换:

  • 工程中通过explicit关键字杜绝编译器的转换尝试

  • 转换构造函数被explicit修饰只能进行显示转换(也就是强制类型转换)

代码实践一:

#include #include class Test{

public: Test()
    {

    }
   explicit Test(int i)
    {

    }
};

int main()
{
     Test t;

     t =6; return 0;
}

输出结果:

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 #include class Test{

public: Test()
    {

    }
   explicit Test(int i)
    {

    }
};

int main()
{
     Test t;

     t =static_cast(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 #include 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#  

注:

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

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

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

2、类类型之间的转换:

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

代码版本一:

#include #include 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 #include 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;
}

输出结果:

root@txp-virtual-machine:/home/txp# g++ test.cpp test.cpp: In function ‘int main()’:
test.cpp:42:15: error: conversion from ‘Test’ to ‘Value’ is ambiguous
     Value v = t;
               ^
test.cpp:41:10: note: candidates are:
     Test t(100);
          ^
test.cpp:31:5: note: Test::operator Value()
     operator Value()
     ^
test.cpp:14:6: note: Value::Value(Test&)
      Value(Test& t)

3、小结:

  • 无法抑制隐式的类型转换函数调用

  • 类型转换函数可能与转换构造函数起冲突

  • 当然工程中可能比较习惯用 Type toType()的公有成员代替类型转换函数(就是换了种写法)

免责声明:本文内容由21ic获得授权后发布,版权归原作者所有,本平台仅提供信息存储服务。文章仅代表作者个人观点,不代表本平台立场,如有问题,请联系我们,谢谢!

本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除。
换一批
延伸阅读

Python由荷兰数学和计算机科学研究学会的吉多·范罗苏姆于1990年代初设计,作为一门叫做ABC语言的替代品。 Python提供了高效的高级数据结构,还能简单有效地面向对象编程。

关键字: python 函数 对象编程

测试数据综合分析的绝佳工具,深受工程师和研究员欢迎

关键字: 后处理分析软件 向导 函数

由上图中可以知道进程地址空间中最顶部的段是栈,代码中调用函数、定义局部变量(但不包含static修饰的变量)或声明的类的实例等等都要使用栈空间,当函数执行完(也就是程序执行超过了这个函数的作用范围的时候),操作系统会把该...

关键字: 进程地址 局部变量 函数

星标/置顶 公众号,硬核文章第一时间送达!链接| https://zhuanlan.zhihu.com/p/274473971题很多,先上题后上答案,便于大家思考问题点:1、C和C的特点与区别?2、C的多态3、虚函数实现...

关键字: 腾讯 函数 进程 AI

程序接口是操作系统为用户提供的两类接口之一,编程人员在程序中通过程序接口来请求操作系统提供服务。面向过程语言最基本的单元是过程和函数。

关键字: 程序接口 过程 函数

星标「嵌入式大杂烩」,一起进步!链接:https://www.cnblogs.com/jozochen/p/8541714.html一、问题复现稳定复现问题才能正确的对问题进行定位、解决以及验证。一般来说,越容易复现的问...

关键字: 嵌入式开发 函数 代码 寄存器

基本上,没有人会将大段的C语言代码全部塞入main()函数。更好的做法是按照复用率高、耦合性低的原则,尽可能的将代码拆分不同的功能模块,并封装成函数。C语言代码的组合千变万化,因此函数的功能可能会比较复杂,不同的输入,常...

关键字: 函数 PEN C语言代码 C语言程序

Part1一、让自己习惯C条款01:视C为一个语言联邦C并不是一个带有一组守则的一体语言:他是从四个次语言(C、Object-OrientedC、Template、STL) 组成的联邦政府,每个次语言都有自己的规约。记住...

关键字: 函数 ASPECT 编译器

为什么会写篇栈变化的文章?做系统分析的话你肯定遇到过一些crash,oops等棘手问题,一般大家都会用gdb,objdump或者addr2line等工具分析pc位置来定位出错的地方。但是这些分析工具背后的本质原理就不见得...

关键字: 函数 ARM C语言 AI

前言:一转眼从事前端已经6年了,从当时的小白到如今大厂的技术专家,中间也走过不少弯路,从今天开始我会持续更新前端技术文章,并且整体的文章会进行体系梳理,整个知识体系分为:基础精讲,框架讲解,框架及工具原理,前端面试题精讲...

关键字: 函数 GE FUNCTION APP
关闭
关闭