我有一个 BigInt
类型,它将大数字作为数字数组 (0-9) 存储在一个名为 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:错误:“const BigInt”类型没有可行的重载运算符[]
m_digitArray[i] = rhs[i];
~~~^~
BigInt.cpp:114:16: 注意:候选函数不可行:'this' 参数具有类型
'const BigInt',但方法未标记为 const
char & BigInt::operator [] (int i){
^
产生 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];
}
关于c++ - const 类型没有可行的重载 operator[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43022066/