编写一个引用类型的函数,用作l值来处理它的r值
Writing a reference-type function to be used as L-value to process its R-value
我注意到网络和书籍中引用类型函数的示例代码都只有一个返回行(就像下面来自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;
}
相关文章:
- 警告处理为错误这里有什么问题
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用流处理接收到的数据
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 基于多个条件处理地图中的所有元素
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 如何用数字处理log(0)
- SSL上的`curl_easy_send`和`curl_asy_recv`:如何处理`CURLE_AGAIN`
- 错误处理.将系统错误代码映射到泛型
- 从文本文件中读取时钟时间和事件时间并进行处理
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- C++,sqlite3.当 BLOB 字段用作查询条件时如何处理它?
- 当更新值用作回调时,如何处理 QT/C++ 中的进度条
- 编写一个引用类型的函数,用作l值来处理它的r值
- 执行取消操作时,boost::asio::yield_text是否可以用作deadline_timer处理程序
- 当宏用作变量名时,是否有任何方法可以跳过宏替换(在预处理期间)
- 如果对象被用作左值或右值,如何检测和处理