我注意到,Web和书籍中用于引用类型函数的示例代码都只有一个返回行(如以下来自MSDN的代码)

class Point
{
public:
  unsigned& x();
private:
  unsigned obj_x;
};

unsigned& Point :: x()
{
  return obj_x;
}

int main()
{
  Point ThePoint;
  ThePoint.x() = 7;
}


我认为,如果我在引用类型的函数中包含更多行(算术表达式,控件结构等),则它们仅在用作常规(R值)函数时才会改变其行为。但是我怎么写一个函数,当它用作L值时,会对它的R值(这里是数字7)做一些算术运算,或者在放入返回变量(这里)?

最佳答案

您的意思很容易理解。但这不能以这种方式实现。

您想要的是在代理对象的帮助下完成的,就像在std::vector<bool>专业化中完成的一样。当像v[i] = true;那样使用它时,v[i]返回具有重载赋值运算符的代理对象,该运算符会使内部位字符串中的ith位升高。

例:

struct A
{
   struct proxy
   {
      proxy(int * x)
         : x_(x)
      {
      }

      proxy & operator = (int v)
      {
         *x_ = v + 2;
         return *this;
      }

      operator int() const
      {
         return *x_;
      }
    private:
      int * x_;
   };

   proxy x_add_2()
   {
      return proxy(&x_);
   }

   int x() const
   {
      return x_;
   }
private:
   int x_;
};

int main(int argc, char* argv[])
{
   A a;
   a.x_add_2() = 2;
   std::cout << a.x() << std::endl;
   return 0;
}

关于c++ - 编写引用类型的函数以用作L值以处理其R值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16957748/

10-12 12:51
查看更多