一个关于 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);
}
我是否可以通过函数原型获得类型强制?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的问题实际上是关于参数和参数的类型是否匹配,那么答案是肯定的。
typedef
不会引入新类型,它只是为现有类型创建别名。变量b
的类型为unsigned int
,就像参数一样,尽管b
是使用 typedef-nameblatherskite
声明的。不过,你的例子并不能很好地证明这一点。所有整数类型在 C++ 中都可以相互转换,因此(忽略范围问题)即使 blatherskite 指定了不同的类型(新类型),代码也会具有已定义的行为。但事实并非如此。所以这也是完全有效的
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. Variableb
has typeunsigned int
, just like the parameter, even thoughb
is declared using typedef-nameblatherskite
.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不需要类型强制。 typedef 只是同一类型的别名,因此您将一个
unsignedshort
传递给一个采用unsignedshort
的函数。No type coercion is needed. The typedef is just an alias for the same type, so you're passing an
unsigned short
to a function that takes anunsigned short
.