重载一元运算符& [英] Overloading unary operator &

查看:141
本文介绍了重载一元运算符&的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑一个带有重载的一元运算符& (地址)。让它 A类

 模板< class C& 
class A
{
public:
C * operator&()
{
return& data;
}
// ...
private:
C data;
}

现在我想传递给某个函数类型 A 以填充其数据。让我们称之为 f

  void f(A * auto_containter)
{
// ...
}

清楚为什么代码下面将不工作(甚至不会编译)。这是因为重载的操作符被调用。

  A a; 
f(& a);

问题如下:



有任何语法将 a 的地址传递到 f ?如果没有,那么对我来说很奇怪为什么它允许重载一元运算符& ,因为它使代码更加错误和难以理解。

使用 boost :: addressof 功能。在任何情况下,是高度怀疑。为什么不使用返回数据地址的命名函数呢?


Let's consider a class with overloaded unary operator & (Address-of). Let it be class A

template <class C>
class A
{
public:
    C * operator &()
    {
        return &data;
    }
    //...
private:
    C data;
}

Now I want to pass to some function a pointer of type A to fill its data. Let us call it f

void f(A * auto_containter)
{
    //...
}

But it is clear why the code bellow wouldn't work (even wouldn't compile). It is because the overloaded operator is called.

A a;
f(&a);

The question is following:

Is there any syntax to pass address of a to f? If no, then for me it is very strange why it is allowed to overload unary operator &, because it makes code more buggy and difficult to understand. Or there are some other reasons?

解决方案

Use boost::addressof function. In any case, overloading unary & is highly dubious. Why do it instead of having a named function that returns the address of your data?

这篇关于重载一元运算符&amp;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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