casting operator - const vs non-const

前端 未结 3 744
野的像风
野的像风 2021-01-11 10:43

I have this code sample:

class Number 
{ 
  int i;
  public:
    Number(int i1): i(i1) {}
    operator int() const {return i;}
};

What are

相关标签:
3条回答
  • 2021-01-11 11:38

    The const version can be called regardless of whether the class Number instance is const or not. If the operator is declared non-const it can only be called on non-const entities - when you try to implicitly use it where it can't be called you'll get a compile error.

    0 讨论(0)
  • 2021-01-11 11:42

    If the conversion operator is not const, you can't convert const objects:

    const Number n(5);
    int x = n; // error: cannot call non-const conversion operator
    
    0 讨论(0)
  • 2021-01-11 11:42

    If you have a function like this:

    void f(const Number& n)
    {
      int n1 = n;
    }
    

    It will start giving compilation error if you remove const in the casting operator.

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