首页 > 解决方案 > 多个运算符通过操作类型覆盖行为

问题描述

因此,假设我正在覆盖描述点的结构的不等式检查。我将其设置为默认比较大小。

我想有一个选项来检查每个值,并且我正在考虑内联的方法。我可以创建一个函数,将其重铸为虚拟结构,以便在比较时具有不同的类型。

struct vec3 {
    double x,y,z;
    struct _all {double x,y,z};
    friend _all All (vec3 &A) { return *(_all*) &vec3;}
    struct _any {double x,y,z};
    friend _any Any (vec3 &A) { return *(_any*) &vec3;}
    friend bool operator < (vec3 &A, double B) { /* does the magnitude check */ }
    friend bool operator < (_all &A, double B) { return A.x<B && A.y < B && A.z<B; }

    friend bool operator < (_any &A, double B) { return A.x<B || A.y < B || A.z<B; }
};

这就是我可以写的全部

if (All(PointA) < Limit) {}

我有一种感觉,这打破了一堆编码实践,但我很难找到任何类似的问题。也许使用构造函数而不是类型更改更安全?或者如果我为我的结构编写一个函数 IsAnyLessThan(double A) 会更清楚吗?

标签: c++operator-overloadingfriend-function

解决方案


推荐阅读