c++ - 为什么这个 c++ 数组运算符的读取变体在一个类中没有被调用

标签 c++ class operator-keyword

<分区>

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


    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

最佳答案

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

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

有一个 helper function对于 C++17 中的那个:

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

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

关于c++ - 为什么这个 c++ 数组运算符的读取变体在一个类中没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34705819/

相关文章:

c++ - 环或环中哪个共享指针应该是弱指针

c++ - 在析构函数中释放内存时出现段错误

C++ 重载运算符两次,一次返回非 const 引用,另一次返回 const 引用,偏好是什么?

c++ - 尝试从复选框更改中获取信号

c++ - CUDA:--ptxas-options=-v 共享内存和 cudaFuncAttributes.sharedSizeBytes 不匹配

c++ - 如何使用多个 SVM 分类器 - 每个分类器都有一个特定的内核 - 作为 "one vs rest classification"方案?

javascript - 创建 GetterSetter 类不起作用

c++ - cpp中dll的引用类

c++ - header 中 namespace 内的运算符声明?

c - 在给定的用户定义函数中,求值顺序是否会无法将源字符串复制到目标字符串?