Const and Non-Const Operator Overloading

前端 未结 2 1115
轻奢々
轻奢々 2020-11-30 02:04

I have a topic I\'m confused on that I need some elaborating on. It\'s operator overloading with a const version and a non-const version.

// non-const
double          


        
相关标签:
2条回答
  • 2020-11-30 02:30

    To supply a code example to complement the answer above:

    Array a(3);
    a[0] = 2.0;  //non-const version called on non-const 'a' object
    
    const Array b(3);
    double var = b[1];  //const version called on const 'b' object
    
    const Array c(3);
    c[0] = 2.0;  //compile error, cannot modify const object
    
    0 讨论(0)
  • 2020-11-30 02:37

    When both versions are available, the logic is pretty straightforward: const version is called for const objects, non-const version is called for non-const objects. That's all.

    In your code sample a is a non-const object, meaning that the non-const version is called in all cases. The const version is never called in your sample.

    The point of having two versions is to implement "read/write" access for non-const objects and only "read" access for const objects. For const objects const version of operator [] is called, which returns a const double & reference. You can read data through that const reference, but your can't write through it.

    0 讨论(0)
提交回复
热议问题