C ++中的const运算符重载问题 [英] Const operator overloading problems in C++

查看:118
本文介绍了C ++中的const运算符重载问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用const版本重载operator()时遇到麻烦:

I'm having trouble with overloading operator() with a 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; }
}

这给了我以下输出:



  • 调用NONconst版本--调用NONconst版本-A(1,1)= 8.8

  • 调用了NONconst版本-错误:您只能更改矩阵的第一行。

如何实现C ++调用operator()的const版本?我正在使用GCC 4.4.0。

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

推荐答案

重载看起来不错,但是您永远不会在const对象上调用它。您可以尝试以下操作:

The overloading looks fine but you never call it on a const object. You can try this:

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

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

这会给您:

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

这篇关于C ++中的const运算符重载问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆