c ++类型转换操作符重载和隐式转换 [英] c++ type cast operator overloading and implicit conversions

查看:127
本文介绍了c ++类型转换操作符重载和隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我重载类型转换运算符,当我需要隐式转换并且找不到一个隐式转换时,我遇到编译错误。考虑一个简单的例子,其中我有一个包含类型(在这种情况下长long)的包装类:

  class my_wrapper 
{
long long state;

public:
my_wrapper(long long _in):state(_in){}

my_wrapper& operator =(const long long rhs)
{
state = rhs;
return * this;
}

操作符long long()
{
return state;
}
};

现在的问题是,如果我想在代码中转换为别的东西假设我在64位为此)以下不工作没有指定两个演员:

  my_wrapper x1 = my_wrapper (5II)。 
void * i1 =(void *)x1; //编译错误:没有合适的转换函数
void * i1 =(void *)(long long)x1; // Works

vs。如果我写了如下:

  long long i1 = 5ll; 
void * i2 =(void *)i1; //工作

不是什么大不了的,但只是好奇,如果它可能指定如果没有其他转换,应该使用long()。



提前感谢... Nick。

(void *)x1 有效地给你的地址 x1.state
你可以简单地实现一个 void * 转换操作符。



  operator void *()
{
return& state;这个的缺点是你现在可以转换



<



幸运的是,您可以在 C ++ 11 中使用显式说明符来防止这种情况:

 显式运算符void *()
{
return& state;
}


if I'm overloading the type cast operator, I'm running into compile errors when an implicit conversion is needed and one can't be found. Consider the simple example where I have a wrapper class that contains a type (in this case a long long):

class my_wrapper
{
    long long state;

public:
    my_wrapper(long long _in) : state(_in) {}

    my_wrapper& operator=(const long long rhs)
    {
        state = rhs;
        return *this;
    }

    operator long long()
    {
        return state;
    }
};

The question now is that if I want to cast in code to something else (eg a void* ... assume that I'm on 64bit for this) the following does not work without specifying two casts:

my_wrapper x1 = my_wrapper(5ll);
void* i1 = (void *) x1; // Compile Error: no suitable conversion function exists
void* i1 = (void *) (long long) x1; // Works

vs. if I had written something like:

long long i1 = 5ll;
void* i2 = (void *) i1; // Works

Not a big deal, but just curious if its possible to specify that the "operator long long()" should be used as the default if there is no other conversion.

Thanks in advance ... Nick.

解决方案

Since (void *)x1 effectively gives you the address of x1.state you could simply implement a void * cast operator.

Like so:

operator void *()
{
    return &state;
}

The drawback of this is that you can now convert my_wrapper to void * implicitly as well.

Luckily, you can prevent this in C++11 by using the explicit specifier:

explicit operator void *()
{
    return &state;
}

这篇关于c ++类型转换操作符重载和隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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