首页 文章

为什么这个读数变量的c数组运算符在一个类中没有被称为[duplicate]

提问于
浏览
0

这个问题在这里已有答案:

在各种示例中,我看到您可以在类中创建不同的运算符以进行读取和写入类数组元素 . 但是当我在Mingw和Borland上尝试这个例子时,它总是调用写操作符 .

class Point3
    {
        float coord[3];
    public:
        float   operator [] (int index) const; // For reading
        float & operator [] (int index);       // For writing
    };

    float Point3::operator [] (int index) const
    {
        printf("reading... \n") ;
        return 123.0*coord[index];
    }

    float & Point3::operator [] (int index)
    {
        printf("writing... \n") ;
        return coord[index];
    }



    int main(int argc, char* argv[]) 
    {
        Point3 xyz ;
        xyz[0] = 1.0 ;
        printf("%3.2f",xyz[0]) ;
        return 0 ;
    }



    output:

    writing...
    writing...
    1.00

1 回答

  • 1

    如果要使用const重载,首先必须创建一个const值:

    printf("%3.2f", static_cast<const Point3 &>(xyz)[0]);
    //              ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    在C 17中有一个helper function

    printf("%3.2f", as_const(xyz)[0]);
    //              ^^^^^^^^
    

    在编程和计算机科学中,“阅读”和“写作”通常不是相互排斥的,而是“阅读”是“写作”的一个子集:您要么拥有对资源的只读访问权限,要么您已阅读并且 - 写访问 . 这就是你应该如何看待这两个重载 .

相关问题