C ++中的static_cast |类型转换运算符

2021年3月21日15:44:58 发表评论 700 次浏览

Cast运算子是

一元运算符

强制将一种数据类型转换为另一种数据类型。

C ++支持四种类型的转换:

1.静态转换2.动态转换3.常量转换4.重新解释转换

静态演员表:

这是可以使用的最简单的类型转换。它是一个

编译时间

它的作用类似于类型之间的隐式转换(例如int到float或指向void *的指针), 它还可以调用显式转换函数(或隐式函数)。

例如

#include <iostream>
using namespace std;
int main()
{
     float f = 3.5;
     int a = f; // this is how you do in C
     int b = static_cast < int >(f);
     cout << b;
}

输出如下:

3

现在, 让我们对代码进行一些更改。

#include <iostream>
using namespace std;
int main()
{
     int a = 10;
     char c = 'a' ;
  
     // pass at compile time, may fail at run time
     int * q = ( int *)&c; 
     int * p = static_cast < int *>(&c);
     return 0;
}

如果编译代码, 则会出现错误:

[Error] invalid static_cast from type 'char*' to type 'int*'

这意味着即使你认为可以将一个特定对象转换为另一个对象, 但非法, static_cast将不允许你执行此操作。

让我们举一个在类之间来回转换对象的例子。

#include <iostream>
#include <string>
using namespace std;
class Int {
     int x;
  
public :
     Int( int x_in = 0)
         : x{ x_in }
     {
         cout << "Conversion Ctor called" << endl;
     }
     operator string()
     {
         cout << "Conversion Operator" << endl;
         return to_string(x);
     }
};
int main()
{
     Int obj(3);
     string str = obj;
     obj = 20;
     string str2 = static_cast <string>(obj);
     obj = static_cast <Int>(30);
     return 0;
}

运行上面的代码:

Conversion Ctor called
Conversion Operator
Conversion Ctor called
Conversion Operator
Conversion Ctor called

让我们尝试了解以上输出:

  1. 什么时候对象被创建, 然后调用构造函数, 在我们的例子中, 该构造函数也是转换构造函数(对于C ++ 14规则, 是位更改)。
  2. 创建时str在......之外对象, 编译器不会因为我们定义了Conversion运算符而引发错误。
  3. 当你做obj = 20, 实际上是在调用转换构造函数。
  4. 当你做str2在......之外static_cast, 它非常类似于字符串str = obj;, 但要进行严格的类型检查。
  5. 当你写obj = static_cast <Int>(30), 你正在将30转换为int使用static_cast。

让我们以涉及继承的示例为例。

#include <iostream>
using namespace std;
class Base {
};
class Derived : public Base {
};
int main()
{
     Derived d1;
     Base* b1 = (Base*)(&d1); // allowed
     Base* b2 = static_cast <Base*>(&d1);
  
     return 0;
}

上面的代码将编译而没有任何错误。

  1. 我们收到了d1并明确地将其投射到基础并存储在b1.
  2. 我们收到了d1并使用static_cast将其转换为基础并存储在b2.

我们知道static_cast会执行严格的类型检查, 让我们稍微更改一下代码以查看一下:

#include <iostream>
using namespace std;
class Base {
};
class Derived : private Base { // Inherited private/protected not public
};
int main()
{
     Derived d1;
     Base* b1 = (Base*)(&d1); // allowed
     Base* b2 = static_cast <Base*>(&d1);
     return 0;
}

尝试编译以上代码, 你看到了什么??编译错误!

[Error] 'Base' is an inaccessible base of 'Derived'

上面的代码将不编译即使你继承为protected。因此, 要使用static_cast, 请将其继承为public。

使用static_cast强制转换为"往返"无效指针。

#include <iostream>
int main()
{
     int i = 10;
     void * v = static_cast < void *>(&i);
     int * ip = static_cast < int *>(v);
     return 0;
}

被认为是行业中最受欢迎的技能之一, 我们拥有自己的编码基础C ++ STL通过激烈的问题解决过程来训练和掌握这些概念。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: