一个关于C ++中类型强制的简单问题 [英] A simple question about type coercion in C++

查看:168
本文介绍了一个关于C ++中类型强制的简单问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个函数原型和一个类型定义:

  int my_function(unsigned short x); 
typedef unsigned short blatherskite;是由标准定义的以下情况:


  int main(int argc,char ** argv){
int result;
blatherskite b;

b = 3;
result = my_function(b);
}

我可以通过函数原型预测类型强制吗?

解决方案

如果你的问题是关于参数的类型和参数是否匹配,那么答案是肯定的。 typedef 不会引入新类型,它只会为现有类型创建别名。变量 b 类型为 unsigned int ,就像参数一样,即使 b 使用typedef-name blatherskite 声明。



您的示例不是非常有利于演示。所有的积分类型都可以在C ++中互相转换,所以(忽略范围问题)代码将会定义行为,即使 blatherskite 指定一个不同的类型(一个新类型)。但它不。所以这也是完全有效的。

  void foo(unsigned int * p); 
...
blatherskite * pb = 0;
foo(pb); //< - 仍然有效


Given a function prototype, and a type definition:

int my_function(unsigned short x);
typedef unsigned short blatherskite;

Is the following situation defined by standard:

int main(int argc, char** argv) {
  int result;
  blatherskite b;

  b=3;
  result = my_function(b);
}

Do I get type coercion predictably via the function prototype?

解决方案

If your question is really about whether the types of the argument and the parameter match, then the answer is yes. typedef does not introduce a new type, it only creates alias for an existing one. Variable b has type unsigned int, just like the parameter, even though b is declared using typedef-name blatherskite.

Your example is not very good for demonstrating that though. All integral types are convertible to each other in C++, so (ignoring range issues) the code would have defined behavior even if blatherskite designated a different type (a new type). But it doesn't. So this is also perfectly valid

void foo(unsigned int* p);
...
blatherskite *pb = 0;
foo(pb); // <- still valid

这篇关于一个关于C ++中类型强制的简单问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆