编写一个引用类型的函数,用作l值来处理它的r值

Writing a reference-type function to be used as L-value to process its R-value

本文关键字:用作 处理 函数 一个 引用类型      更新时间:2023-10-16

我注意到网络和书籍中引用类型函数的示例代码都只有一个返回行(就像下面来自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)做一些算术,或者在把它放入返回变量(这里是obj_x)之前检查它是否符合一些条件?

你的意思是非常违反直觉。但这是不可能实现的。

您想要的通常是在代理对象的帮助下完成的,就像在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;
}