我正在实现一个matrix类,并试图重载一些运算符。 问题出在+运算符上:
/**
* define a sum of an int with an IntMatrix - IntMatrix as first parameter
* @return the sum of the two
*/
IntMatrix operator+(int);
这是在类本身中定义的。 为了使用make this运算符变得对称,我在类外部的相同命名空间下重新定义了它:
IntMatrix operator+(int, const IntMatrix&);
例如,以下代码可以工作:
IntMatrix mat_1;
mat_2 = mat_1 + 4;
但该代码不:
IntMatrix mat_1;
mat_2 = 4 + mat_1;
由于某种原因,编译器根本无法识别这个运算符(它写它时有一个未定义的引用)。 你能找出错误吗?
编译器不知道您的运算符+
是可交换的,编译器不会假设任何事情。 基本上是为了线
mat_2 = 4 + mat_1;
编译器正在搜索运算符+
,该运算符采用类型为Int
的第一个参数和类型为IntMatrix
的第二个参数(未定义)。
你也得给这个案子下个定义。 如果运算是可交换的,那就很容易了:
IntMatrix operator+(const IntMatrix&matrix, int number) [
return number + matrix; // call the other operator you already have.
}
coliru上的现场演示