重载运算符 + C++ 时出错
Error with overloaded operator+ C++
我在尝试使用重载运算符+添加两个 2D 矩阵时遇到问题。我已经成功地将两个矩阵分配给两个不同的数组。
我的错误是:
在函数 'mathadd::matrices mathadd::operator+(mathadd::matrices&, mathadd::matrices&)' 中:
调用"mathadd::matrices::matrices(double&)"没有匹配函数
候选人是: MathAdd::Matrices::Matrices(const mathadd::matrices&)
在我的 int main() {} 中,此错误的主要部分是:
matrices sample;
double array1[4][4], array2[4][4], add[4][4];
add[4][4] = array1[4][4] + array2[4][4];
重载运算符定义为:
matrices operator +(matrices& p1, matrices& p2) { double addition[4][4]; for (int y = 0; y < 4; ++y ) { for (int x = 0; x < 4; ++x ) { addition[4][4] = p1.get_array1() + p2.get_array2(); } } matrices sum(addition[4][4]); // This is where the error is. return sum; }
我的班级看起来像这样
class matrices
{
public:
matrices();
void assignment(double one[4][4], double two[4][4]);
double get_array1() const {return first_array[4][4];}
double get_array2() const {return second_array[4][4];}
matrices operator +(matrices& p1, matrices& p2);
private:
double first_array[4][4], second_array[4][4];
//Initialized to 0 in constructor.
};
我不明白这个错误是什么意思,我将不胜感激任何帮助,以了解它的含义以及如何修复它。
addition[4][4]
是一个双重越界数组访问,用于从 addition
命名的第五个double[]
获取第五个double
。只需将名称传递addition
而不是addition[4][4]
matrices sum(addition[4][4])
.
所以应该是
matrices sum(addition);
return sum;
这只是编译器错误的根源。代码中也有许多逻辑错误,例如我前面提到的内部for
-循环中的越界数组访问。您将不得不修复这些问题,否则将获得未定义的行为。
您会收到错误,因为您的operator +
是为 matrices
类型的对象定义的,而不是为 double
秒的 2D 数组定义的。您需要在添加矩阵之前构造矩阵,如下所示:
首先,为matrices
添加一个需要double[4][4]
的构造函数。然后,将operator +
的签名更改为static
,并对其参数进行const
引用:
static matrices operator +(const matrices& p1, const matrices& p2);
现在你可以这样写:
matrices add = matrices(array1) + matrices(array2);
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 用pybind11包装C++抽象类时出错
- 为x86而非x64编译时出错
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 为重写std::exception的库生成swig接口时出错
- 导入/导出变量时出错
- PrintWindow函数在notepad.exe中出错