如何避免隐式转换非构造函数? (C ++)

编程入门 行业动态 更新时间:2024-10-23 21:34:51
本文介绍了如何避免隐式转换非构造函数? (C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何避免对非构造函数的隐式转换? 我有一个函数,它接受一个整数作为参数, 但是该函数也将采用字符,bools ,和longs。 我相信这是通过隐式转换来实现的。 我如何避免这种情况,使函数只接受匹配类型的参数,并拒绝编译否则? 有一个关键字explicit,但它不适用于非构造函数。 :\ 我该怎么办?

How do I avoid implicit casting on non-constructing functions? I have a function that takes an integer as a parameter, but that function will also take characters, bools, and longs. I believe it does this by implicitly casting them. How can I avoid this so that the function only accepts parameters of a matching type, and will refuse to compile otherwise? There is a keyword "explicit" but it does not work on non-constructing functions. :\ what do I do?

以下程序编译,虽然我不想这样做:

The following program compiles, although I'd like it not to:

#include <cstdlib> //the function signature requires an int void function(int i); int main(){ int i{5}; function(i); //<- this is acceptable char c{'a'}; function(c); //<- I would NOT like this to compile return EXIT_SUCCESS; } void function(int i){return;}

*请务必指出任何滥用术语和假设。

*please be sure to point out any misuse of terminology and assumptions

推荐答案

c $ c> char 自动被提升为 int 。

You can't directly, because a char automatically gets promoted to int.

您可以借助一个技巧:创建一个以 char 为参数的函数,它。它会编译,但你会得到一个链接器错误:

You can resort to a trick though: create a function that takes a char as parameter and don't implement it. It will compile, but you'll get a linker error:

void function(int i) { } void function(char i);

使用 char 参数调用函数打破构建。

Calling the function with a char parameter will break the build.

请参见 ideone/2SRdM

术语:非建构函数?你的意思是一个不是构造函数的函数?

Terminology: non-construcing functions? Do you mean a function that is not a constructor?

更多推荐

如何避免隐式转换非构造函数? (C ++)

本文发布于:2023-11-16 11:49:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1604018.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   隐式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!