你可以使用关键字explicit来阻止方法参数的自动转换吗? [英] Can you use keyword explicit to prevent automatic conversion of method parameters?

查看:124
本文介绍了你可以使用关键字explicit来阻止方法参数的自动转换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以使用C ++关键字'explicit'用于类的构造函数,以防止类型的自动转换。你可以使用这个命令来防止类方法的参数转换吗?

I know you can use C++ keyword 'explicit' for constructors of classes to prevent an automatic conversion of type. Can you use this same command to prevent the conversion of parameters for a class method?

我有两个类成员,一个使用bool作为参数,另一个unsigned int。当我使用int调用函数时,编译器将param转换为bool并调用错误的方法。我知道最终我会替换bool,但现在不想打破其他例程,因为这个新的例程开发。

I have two class members, one which takes a bool as a param, the other an unsigned int. When I called the function with an int, the compiler converted the param to a bool and called the wrong method. I know eventually I'll replace the bool, but for now don't want to break the other routines as this new routine is developed.

感谢

推荐答案

不,你不能使用显式,但你可以这样做:

No, you can't use explicit, but you can do this instead:

class ClassThatOnlyTakesBoolsAndUIntsAsArguments
{
public:
  void Method(bool arg1);
  void Method(unsigned int arg1);

  // Below just an example showing how to do the same thing with more arguments
  void MethodWithMoreParms(bool arg1, SomeType& arg2);
  void MethodWithMoreParms(unsigned int arg1, SomeType& arg2);

private:
  template<typename T>
  void Method(T arg1);

  // Below just an example showing how to do the same thing with more arguments
  template<typename T>
  void MethodWithMoreParms(T arg1, SomeType& arg2);
};

对于每个使用 bool unsigned int

这将强制用户总是显式地调用bool或unsigned int版本。

This will force the user to always explicitly call the bool or unsigned int version.

任何尝试调用 bool 或<$ c以外的方法 $ c> unsigned int 将无法编译,因为成员是私有的,受限于可见性规则的标准例外,当然(朋友,内部调用等)。如果有访问调用private方法的东西,你会得到一个链接器错误。

Any attempt to call Method with a type other than bool or unsigned int will fail to compile because the member is private, subject to the standard exceptions to visibility rules, of course (friend, internal calls, etc.). If something that does have access calls the private method, you will get a linker error.

这篇关于你可以使用关键字explicit来阻止方法参数的自动转换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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