Type Casting

Type Casting

Converting an expression of a given type into another type is known as  type-casting. We have already seen some ways to type cast:

Implicit conversion

Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:

1
2
3
short a=2000;
int b;
b=a;


Here, the value of  a has been promoted from  short to  int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types ( short to  intint to  floatdouble to  int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.

Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions. For example:

1
2
3
4
5
class A {};
class B { public: B (A a) {} };

A a;
B b=a;


Here, a implicit conversion happened between objects of  class A and  class B, because  B has a constructor that takes an object of class  A as parameter. Therefore implicit conversions from  A to  B are allowed.

Explicit conversion

C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:

1
2
3
4
short a=2000;
int b;
b = (int) a;    // c-like cast notation
b = int (a);    // functional notation 


The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors. For example, the following code is syntactically correct:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// class type-casting
#include <iostream>
using namespace std;

class CDummy {
    float i,j;
};

class CAddition {
	int x,y;
  public:
	CAddition (int a, int b) { x=a; y=b; }
	int result() { return x+y;}
};

int main () {
  CDummy d;
  CAddition * padd;
  padd = (CAddition*) &d;
  cout << padd->result();
  return 0;
}
 


The program declares a pointer to  CAddition, but then it assigns to it a reference to an object of another incompatible type using explicit type-casting:

 
padd = (CAddition*) &d;


Traditional explicit type-casting allows to convert any pointer into any other pointer type, independently of the types they point to. The subsequent call to member  resultwill produce either a run-time error or a unexpected result.

In order to control these types of conversions between classes, we have four specific casting operators:  dynamic_castreinterpret_caststatic_cast and  const_cast. Their format is to follow the new type enclosed between angle-brackets ( <>) and immediately after, the expression to be converted between parentheses.

dynamic_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
static_cast <new_type> (expression)
const_cast <new_type> (expression)

The traditional type-casting equivalents to these expressions would be:

(new_type) expression
new_type (expression)

but each one with its own special characteristics:

dynamic_cast


dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

Therefore,  dynamic_cast is always successful when we cast a class to one of its base classes:

1
2
3
4
5
6
7
8
class CBase { };
class CDerived: public CBase { };

CBase b; CBase* pb;
CDerived d; CDerived* pd;

pb = dynamic_cast<CBase*>(&d);     // ok: derived-to-base
pd = dynamic_cast<CDerived*>(&b);  // wrong: base-to-derived 


The second conversion in this piece of code would produce a compilation error since base-to-derived conversions are not allowed with  dynamic_cast unless the base class is polymorphic.

When a class is polymorphic,  dynamic_cast performs a special checking during runtime to ensure that the expression yields a valid complete object of the requested class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// dynamic_cast
#include <iostream>
#include <exception>
using namespace std;

class CBase { virtual void dummy() {} };
class CDerived: public CBase { int a; };

int main () {
  try {
    CBase * pba = new CDerived;
    CBase * pbb = new CBase;
    CDerived * pd;

    pd = dynamic_cast<CDerived*>(pba);
    if (pd==0) cout << "Null pointer on first type-cast" << endl;

    pd = dynamic_cast<CDerived*>(pbb);
    if (pd==0) cout << "Null pointer on second type-cast" << endl;

  } catch (exception& e) {cout << "Exception: " << e.what();}
  return 0;
}
Null pointer on second type-cast


Compatibility note: dynamic_cast requires the Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers support this feature as an option which is disabled by default. This must be enabled for runtime type checking using dynamic_cast to work properly.

The code tries to perform two dynamic casts from pointer objects of type  CBase* ( pba and  pbb) to a pointer object of type  CDerived*, but only the first one is successful. Notice their respective initializations:

1
2
CBase * pba = new CDerived;
CBase * pbb = new CBase;


Even though both are pointers of type  CBase*pba points to an object of type  CDerived, while  pbb points to an object of type  CBase. Thus, when their respective type-castings are performed using  dynamic_castpba is pointing to a full object of class  CDerived, whereas  pbb is pointing to an object of class  CBase, which is an incomplete object of class  CDerived.

When  dynamic_cast cannot cast a pointer because it is not a complete object of the required class -as in the second conversion in the previous example- it returns a null pointer to indicate the failure. If  dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type  bad_cast is thrown instead.

dynamic_cast can also cast null pointers even between pointers to unrelated classes, and can also cast pointers of any type to void pointers ( void*).

static_cast

static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided.

1
2
3
4
class CBase {};
class CDerived: public CBase {};
CBase * a = new CBase;
CDerived * b = static_cast<CDerived*>(a);


This would be valid, although  b would point to an incomplete object of the class and could lead to runtime errors if dereferenced.

static_cast can also be used to perform any other non-pointer conversion that could also be performed implicitly, like for example standard conversion between fundamental types:

1
2
double d=3.14159265;
int i = static_cast<int>(d); 


Or any conversion between classes with explicit constructors or operator functions as described in "implicit conversions" above.

reinterpret_cast

reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.

It can also cast pointers to or from integer types. The format in which this integer value represents a pointer is platform-specific. The only guarantee is that a pointer cast to an integer type large enough to fully contain it, is granted to be able to be cast back to a valid pointer.

The conversions that can be performed by  reinterpret_cast but not by  static_cast have no specific uses in C++ are low-level operations, whose interpretation results in code which is generally system-specific, and thus non-portable. For example:

1
2
3
4
class A {};
class B {};
A * a = new A;
B * b = reinterpret_cast<B*>(a);


This is valid C++ code, although it does not make much sense, since now we have a pointer that points to an object of an incompatible class, and thus dereferencing it is unsafe.

const_cast

This type of casting manipulates the constness of an object, either to be set or to be removed. For example, in order to pass a const argument to a function that expects a non-constant parameter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// const_cast
#include <iostream>
using namespace std;

void print (char * str)
{
  cout << str << endl;
}

int main () {
  const char * c = "sample text";
  print ( const_cast<char *> (c) );
  return 0;
}
sample text


typeid

typeid allows to check the type of an expression: 

typeid (expression)

This operator returns a reference to a constant object of type  type_info that is defined in the standard header file  <typeinfo>. This returned value can be compared with another one using operators  == and  != or can serve to obtain a null-terminated character sequence representing the data type or class name by using its  name() member.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// typeid
#include <iostream>
#include <typeinfo>
using namespace std;

int main () {
  int * a,b;
  a=0; b=0;
  if (typeid(a) != typeid(b))
  {
    cout << "a and b are of different types:\n";
    cout << "a is: " << typeid(a).name() << '\n';
    cout << "b is: " << typeid(b).name() << '\n';
  }
  return 0;
}
a and b are of different types:
a is: int *
b is: int  


When  typeid is applied to classes  typeid uses the RTTI to keep track of the type of dynamic objects. When typeid is applied to an expression whose type is a polymorphic class, the result is the type of the most derived complete object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// typeid, polymorphic class
#include <iostream>
#include <typeinfo>
#include <exception>
using namespace std;

class CBase { virtual void f(){} };
class CDerived : public CBase {};

int main () {
  try {
    CBase* a = new CBase;
    CBase* b = new CDerived;
    cout << "a is: " << typeid(a).name() << '\n';
    cout << "b is: " << typeid(b).name() << '\n';
    cout << "*a is: " << typeid(*a).name() << '\n';
    cout << "*b is: " << typeid(*b).name() << '\n';
  } catch (exception& e) { cout << "Exception: " << e.what() << endl; }
  return 0;
}
a is: class CBase *
b is: class CBase *
*a is: class CBase
*b is: class CDerived


Note: The string returned by member name of type_info depends on the specific implementation of your compiler and library. It is not necessarily a simple string with its typical type name, like in the compiler used to produce this output. 

Notice how the type that  typeid considers for pointers is the pointer type itself (both  a and  b are of type  class CBase *). However, when  typeid is applied to objects (like  *aand  *btypeid yields their dynamic type (i.e. the type of their most derived complete object).

If the type  typeid evaluates is a pointer preceded by the dereference operator ( *), and this pointer has a null value,  typeid throws a  bad_typeid exception.

What our compiler returned in the calls  type_info::name in the this example, our compiler generated names that are easily understandable by humans, but this is not a requirement: a compiler may just return any string.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明
Raycasting算法是一种用于计算二维或三维场景中可见性和光线投射的算法。它的基本思想是从视点发射一条射线,检测它是否与场景中的物体相交,如果相交,则确定相交点的位置和法向量,并计算出光线在该点的颜色值。这个过程可以通过递归或迭代来实现,直到达到某个终止条件为止。 在二维场景中,Raycasting算法通常用于实现2D游戏中的碰撞检测和可见性计算。在三维场景中,它可以用于实现3D游戏中的光线投射和阴影计算。 Raycasting算法的基本步骤如下: 1. 确定视点和视线方向。 2. 从视点发射一条射线。 3. 检测射线是否与场景中的物体相交。 4. 如果相交,则确定相交点的位置和法向量,并计算出光线在该点的颜色值。 5. 如果没有相交,则将颜色值设置为背景色。 6. 重复步骤2-5,直到所有像素都被处理完毕。 下面是一个简单的Python实现示例: ```python import pygame from pygame.locals import * # 初始化Pygame pygame.init() # 设置窗口大小和标题 screen_width = 640 screen_height = 480 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Raycasting Demo") # 定义场景中的墙壁 walls = [ ((0, 0), (0, screen_height)), ((0, 0), (screen_width, 0)), ((screen_width, 0), (screen_width, screen_height)), ((0, screen_height), (screen_width, screen_height)), ((100, 100), (200, 100)), ((200, 100), (200, 200)), ((200, 200), (100, 200)), ((100, 200), (100, 100)) ] # 定义视点和视线方向 player_pos = (150, 150) player_angle = 0 # 定义射线的数量和角度间隔 num_rays = 60 ray_angle = 60 / num_rays # 主循环 while True: # 处理事件 for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() # 清空屏幕 screen.fill((255, 255, 255)) # 绘制场景中的墙壁 for wall in walls: pygame.draw.line(screen, (0, 0, 0), wall[0], wall[1], 2) # 发射射线并绘制结果 ray_angle = player_angle - 30 for i in range(num_rays): # 计算射线的方向向量 ray_dir = (math.cos(ray_angle), math.sin(ray_angle)) # 计算射线与场景中的墙壁的交点 min_dist = float("inf") for wall in walls: intersect = get_intersect(player_pos, ray_dir, wall) if intersect: dist = distance(player_pos, intersect) if dist < min_dist: min_dist = dist closest_intersect = intersect # 绘制射线 pygame.draw.line(screen, (255, 0, 0), player_pos, closest_intersect) # 计算射线的长度和颜色 ray_length = min_dist * math.cos(math.radians(ray_angle - player_angle)) shade = int(255 - ray_length * 10) if shade < 0: shade = 0 color = (shade, shade, shade) # 绘制射线的视觉效果 pygame.draw.rect(screen, color, (i * 10, screen_height - ray_length, 10, ray_length)) # 更新射线的角度 ray_angle += ray_angle # 更新视点的位置和角度 keys = pygame.key.get_pressed() if keys[K_LEFT]: player_angle -= 5 if keys[K_RIGHT]: player_angle += 5 if keys[K_UP]: player_pos = (player_pos[0] + math.cos(math.radians(player_angle)) * 5, player_pos[1] + math.sin(math.radians(player_angle)) * 5) if keys[K_DOWN]: player_pos = (player_pos[0] - math.cos(math.radians(player_angle)) * 5, player_pos[1] - math.sin(math.radians(player_angle)) * 5) # 绘制视点 pygame.draw.circle(screen, (0, 255, 0), player_pos, 5) # 更新屏幕 pygame.display.update() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值