对于const类型,没有可行的重载operator []

时间:2017-03-25 21:17:45

标签: c++ arrays operator-overloading

我有一个类型BigInt,它将一个数字数组(0-9)存储在名为private m_digitArray的char数组中。 我试图重载数组访问操作符[],它可以访问和分配char值。

然后我尝试重载赋值运算符=,它给了我上面提到的错误。

我哪里错了?如何将值(从本质上复制)从一个BigInt对象传输到另一个对象?

这是代码

BigInt.h

#include <iostream>
using namespace std;

class BigInt{
private:
    // Object Data
    char *m_digitArray;
    unsigned int m_digitArraySize;
    bool m_isPositive;

    // Private Methods
    int getNumOfDigits(int number);
    void reverseArray(char arr[], int start, int end);

public:
    // Constructors
    BigInt();
    BigInt(int numOfDigits);
    BigInt(const BigInt &bi);
    BigInt(const string &number);

    // Access
    int getSize() const;
    bool isPositive() const;
    char &operator [] (int);
};

BigInt.cpp

int BigInt::getSize() const {
        return m_digitArraySize;
    }

    bool BigInt::isPositive() const {
        return m_isPositive;
    }

    char & BigInt::operator [] (int i){
        if(i > m_digitArraySize-1){
            cerr << "Error: Array index out of bounds!" << endl;
            exit(0);
        }
        return m_digitArray[i];
    }

    BigInt & BigInt::operator = (const BigInt &rhs){
        if(this != &rhs){
            m_digitArraySize = rhs.getSize();
            m_isPositive = rhs.isPositive();
            m_digitArray = new char[m_digitArraySize];
            for (int i = 0; i < m_digitArraySize; ++i){
                m_digitArray[i] = rhs[i];
            }
        }
        return *this;
    }

错误

BigInt.cpp:129:25: error: no viable overloaded operator[] for type 'const BigInt' m_digitArray[i] = rhs[i]; ~~~^~ BigInt.cpp:114:16: note: candidate function not viable: 'this' argument has type 'const BigInt', but method is not marked const char & BigInt::operator [] (int i){ ^ 1 error generated.

1 个答案:

答案 0 :(得分:1)

感谢@DeiDei指出我需要两个独立的重载。我想我误读了错误提示。

通过将其添加到头文件中来修复它:

char operator [] (int) const;

这是实施:

char BigInt::operator [] (int i) const{
    if(i > m_digitArraySize-1){
        cerr << "Error: Array index out of bounds!" << endl;
        exit(0);
    }
    return m_digitArray[i];
}