[英]How to check which constructor is used in C++
I modified the question here. 我在这里修改了问题。 Now it looks muck like a answer, :).
现在看起来像一个答案,:)。 Thank you all for sort this out.
谢谢大家解决这个问题。
I have some overloaded constructor in my class, Like this 我的课上有一些重载的构造函数,像这样
#include <string>
#ifdef EXPLICIT_ENUM_CONVERSION
enum struct E
#else
enum E
#endif
{
A,
B
};
class A
{
public:
A(unsigned int i){};
A(std::string const& s){};
};
And a function declaration that actually accept A as a parameter 以及实际上接受A作为参数的函数声明
void func(const class A& a)
{
}
But the caller is invoking it by passing a enum
. 但是调用者通过传递
enum
来调用它。
int main()
{
#ifdef EXPLICIT_ENUM_CONVERSION
E e=E::A;
func((unsigned int)e);
#else
E e=A;
func(e);
#endif
}
Question: By commenting out the A(unsigned)
and compile again to get an error, I can tell that the constructor that is used. 问题:通过注释掉
A(unsigned)
并再次编译以获取错误,我可以知道所使用的构造函数。 But is there a better way to tell how the types are converted from the gcc
command line or objdump
the result? 但是,有没有更好的方法来说明如何从
gcc
命令行或objdump
结果转换类型呢?
Answer: If compiling with -O0 and then use objdump -CSr, the class constructor used is shown from the objdump. 答案:如果使用-O0进行编译,然后使用objdump -CSr,则会从objdump中显示所使用的类构造函数。
Question: is there any way to prevent the enum
to unsigned
automatic conversion with gcc? 问题:有什么方法可以防止用gcc将
enum
转换为unsigned
自动转换?
Answer: See the answer I picked. 答:请参阅我选择的答案。 The scoped enum is introduced in C++11 and can satisfy the purpose.
范围枚举是在C ++ 11中引入的,可以满足目的。 You can check the code within EXPLICIT_ENUM_CONVERSION.
您可以在EXPLICIT_ENUM_CONVERSION中检查代码。
Here are 3 suggestions depending on your goal: 根据您的目标,这里有3条建议:
If you want to understand conversion rules better: 如果您想更好地理解转换规则 :
If you want to find some bug : 如果您想找到一些错误 :
or break down your code into smaller steps, eg 或将您的代码分解为更小的步骤,例如
E e; auto i = static_cast<u32>(e); func(i);
static_cast<u32>(e)
uses explicitly typed initializer idiom (see Effective Modern C++ Item 6) static_cast<u32>(e)
使用显式类型的初始化器惯用语(请参阅Effective Modern C ++项目6)
If you want to avoid bugs , you should avoid too complex implicit conversions and be wary of user-defined conversion functions ( More Effective C++ Item 5). 如果要避免错误 ,则应避免过于复杂的隐式转换,并要警惕用户定义的转换功能( 更有效的C ++项目5)。 For instance:
例如:
explicit A(u32 i){};
explicit A(u32 i){};
enum class E{...}
enum class E{...}
A(E enumElement){};
A(E enumElement){};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.