在某些数据结构中,如果成员的值是在访问时从其他数据成员计算出来的,而不是存储的,这将很有用。
例如,典型的rect类可能会将其left、top、right和bottom坐标存储在成员数据字段中,并为需要相对尺寸而不是绝对尺寸的客户端提供基于这些值返回计算宽度和高度的getter 方法职位。
struct rect
{
int left, top, right, bottom;
// ...
int get_width() const { return right - left; }
int get_height() const { return bottom - top; }
};
这个实现允许我们获取和设置矩形边的绝对坐标,
float center_y = (float)(box.top + box.bottom) / 2.0;
另外为了获得它的相对尺寸,尽管使用了稍微不同的方法调用运算符表达式语法:
float aspect = (float)box.get_width() / (float)box.get_height();
问题
然而,有人可能会争辩说,存储相对宽度和高度而不是绝对右下角坐标同样有效,并且要求需要计算右下角值的客户端使用getter方法。
我的解决方案
为了避免需要记住哪种情况需要方法调用和数据成员访问运算符语法,我提出了一些适用于当前稳定 gcc 和 clang 编译器的代码。下面是一个rect数据结构的全功能示例实现:
#include <iostream>
struct rect
{
union {
struct {
union { int l; int left; };
union { int t; int top; };
union { int r; int right; };
union { int b; int bot; int bottom; };
};
struct {
operator int() {
return ((rect*)this)->r - ((rect*)this)->l;
}
} w, width;
struct {
operator int() {
return ((rect*)this)->b - ((rect*)this)->t;
}
} h, height;
};
rect(): l(0), t(0), r(0), b(0) {}
rect(int _w, int _h): l(0), t(0), r(_w), b(_h) {}
rect(int _l, int _t, int _r, int _b): l(_l), t(_t), r(_r), b(_b) {}
template<class OStream> friend OStream& operator<<(OStream& out, const rect& ref)
{
return out << "rect(left=" << ref.l << ", top=" << ref.t << ", right=" << ref.r << ", bottom=" << ref.b << ")";
}
};
/// @brief Small test program showing that rect.w and rect.h behave like data members
int main()
{
rect t(3, 5, 103, 30);
std::cout << "sizeof(rect) is " << sizeof(rect) << std::endl;
std::cout << "t is " << t << std::endl;
std::cout << "t.w is " << t.w << std::endl;
std::cout << "t.h is " << t.h << std::endl;
return 0;
}
我在这里做的有什么问题吗?
关于嵌套空结构类型的隐式转换运算符中的指针转换,即这些行:
return ((rect*)this)->r - ((rect*)this)->l;
感觉很脏,好像我可能违反了良好的 C++ 风格约定。如果我的解决方案的这个或其他方面是错误的,我想知道原因是什么,最终,如果这是不好的做法,那么是否有一种有效的方法来实现相同的结果。