Problems with overloading the Const statement in C ++

I am having problems overloading the operator () with the const version:

#include <iostream>
#include <vector>
using namespace std;

class Matrix {
public:
    Matrix(int m, int n) { 
        vector<double> tmp(m, 0.0);
        data.resize(n, tmp);
    }
    ~Matrix() { }


    const double & operator()(int ii, int jj) const {
        cout << " - const-version was called - ";
        return data[ii][jj];
    }

    double & operator()(int ii, int jj) {
        cout << " - NONconst-version was called - ";
        if (ii!=1) {
            throw "Error: you may only alter the first row of the matrix.";
        }
        return data[ii][jj];
     }


protected:  
    vector< vector<double> > data;
};

int main() {
try {
    Matrix A(10,10);
    A(1,1) = 8.8;
    cout << "A(1,1)=" << A(1,1) << endl;
    cout << "A(2,2)=" << A(2,2) << endl;
    double tmp = A(3,3);
} catch (const char* c) { cout << c << endl; }
}

This gives me the following result:

  • NONconst-version was called - - NONconst-version was called - A (1,1) = 8.8
  • NONconst-version was called - Error: you can only change the first row of the matrix.

How can I achieve this C ++ call to the const version of the operator ()? I am using GCC 4.4.0.

+3
source share
5 answers

Overloading looks fine, but you never call it in a const object. You can try the following:

void foo(const Matrix& A) {
  cout << "A(1,1)=" << A(1,1) << endl;
}

Matrix A(10,10);
foo(A);

This gives you:

 - const-version was called - A(1,1)=0
+3
source

The object to which you call the on method must be const, for example.

cout << "A(2,2)=" << (*static_cast<const Matrix*>(&A))(2,2) << endl;
+2

, const non-const , . , -, , :

class Proxy
{
  Matrix& m;
  int x, y;
public:
  ...
// mutating operations
  operator double&() { check(); return m.index(x,y); }
  double& operator=(double d) { check(); return m.index(x,y)=d; }
// ... other mutating operations (+=, ...) analogously

// nonmutating ops
  operator double() { return m.const_index(x, y); }
  operator const double&() // ... same
};

Proxy Matrix::operator(int x, int y)
{
  return Proxy(*this, x, y);
}

, check() ( index()), index() const_index() - , .

+1

const_cast < > () const.

, , double? , const, .

0
source

You have different methods with different functionality, so give them different names. Then you do not need to have an object constjust to call what you want.

You can still make operator() constan alternative function call if you have a const object. But alternative functionality should be placed in a function with a descriptive name.

How to get a handle constto an object, use static_cast< const Matrix & >( A ).

0
source

Source: https://habr.com/ru/post/1736846/


All Articles