如何避免隐式转换非构造函数? (C ++) [英] How do I avoid implicit casting on non-constructing functions? (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.
术语:非建构函数?你的意思是一个不是构造函数的函数?
Terminology: non-construcing functions? Do you mean a function that is not a constructor?
这篇关于如何避免隐式转换非构造函数? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!