C++错误:无法用int初始化Array<int>&类型引用的修复方案
修复Matrix类operator[]返回类型不匹配的错误
问题根源
你的Array模板类的operator[]被错误地硬编码为返回int&和const int&,但模板类Array<T>的元素类型应该是T,而非固定的int。当Matrix中的data是Array<Array<T>>类型时,调用data[row]实际返回的是int&,但Matrix的operator[]需要返回Array<T>&,类型不匹配就触发了报错。
修复方案
将Array类的operator[]返回类型改为对应模板参数的引用类型:
template<typename T> class Array { public: Array(): len{0}, buf{nullptr} { } explicit Array(int len) : len{len}, buf{new T[len]} { } // 请确保正确实现拷贝构造、移动构造、析构函数 T& operator[](int index) { if (!in_bounds(index)) throw std::string("Exception operator[](" + std::to_string(index) + ") Out Of Range"); return buf[index]; } const T& operator[](int index) const { if (!in_bounds(index)) throw std::string("Exception operator[](" + std::to_string(index) + ") Out Of Range"); return buf[index]; } private: int len; T* buf; bool in_bounds(int index) const { return index >= 0 && index < len; } };
修复后验证
修改后,当Matrix的data是Array<Array<T>>时,data[row]调用的是Array<Array<T>>的operator[],返回的是Array<T>&,与Matrix的operator[]返回类型完全匹配,错误会被解决。
另外,务必补全Array类的拷贝构造、移动构造和析构函数,避免内存泄漏或浅拷贝问题。
内容的提问来源于stack exchange,提问作者Neeraja
相关产品推荐
相关产品推荐

