为什么我的隐式转换函数不起作用?

发布于 2024-12-03 20:48:48 字数 571 浏览 0 评论 0原文

我有一个包装类,我想修改数据并将其转换回其原始类型。

class A
{
public:
    A ( unsigned __int64 _a ) : a (_a)
    {
    }
    operator unsigned __int64 () const
    {
        return a;
    }
    unsigned __int64 a;
}; 

我希望此类的对象隐式转换回 unsigned __int64,但失败了。

比如说,

 A a( 0x100ull );
 unsigned __int64 b = (a >> 16);  // Error

编译器给出 C2678 错误,找不到运算符或没有可接受的转换。 看来这个函数 operator unsigned __int64 () const 不起作用。


更具体地说,编译器说没有可接受的转换。我不能接受抱怨,因为我已经给出了很好的抱怨。有人可以使其合法化吗?

I have a wrapper class and I want to modify the data and convert it back to its original type.

class A
{
public:
    A ( unsigned __int64 _a ) : a (_a)
    {
    }
    operator unsigned __int64 () const
    {
        return a;
    }
    unsigned __int64 a;
}; 

I want the object of this class to implicitly convert back to unsigned __int64, but it failed.

Say,

 A a( 0x100ull );
 unsigned __int64 b = (a >> 16);  // Error

Compiler gives C2678 error, no operator found or there is no acceptable conversion.
It seems this function operator unsigned __int64 () const doesn't work.


To be more specific, compiler says there is no acceptable conversion. I cannot accept the complain, because I have already given a good one. Can someone legitimize it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

农村范ル 2024-12-10 20:48:48

它不起作用,因为您还没有为您的类创建一个接受整数并对其执行某些操作的 operator>> 重载。

我猜您正在尝试对 int 进行右移,但我不确定重载您的 operator>> 是一个好主意,因为这些运算符在上下文中像这样,通常用于流媒体。之后它可能会让代码的读者或维护者感到困惑。

请参阅此处了解有关运算符重载的更多信息

也许重新考虑您的实施策略?

It doesn't work because you haven't created an operator>> overload for your class that takes an integer and does something with it.

I'm guessing you're trying to do a right shift on your int, but I'm not sure that overloading your operator>> is a good idea for that, as these operators in a context like that, are normally used for streaming. It might confuse a reader or maintainer of your code afterwards.

See here for more info on operator overloading

Perhaps rethink your implementation strategy?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文