C++ Can';t调用重载运算符C++;
我不能调用重载+运算符来对我的两个包装器对象求和 Vector.cpp中的代码:C++ Can';t调用重载运算符C++;,c++,operator-overloading,C++,Operator Overloading,我不能调用重载+运算符来对我的两个包装器对象求和 Vector.cpp中的代码: //Overload operators Vector operator + (const Vector & lhc, const Vector& rhc) { long shorterLength; if(lhc.numberOfElements > rhc.numberOfElements) { shorterLength = rhc.number
//Overload operators
Vector operator + (const Vector & lhc, const Vector& rhc)
{
long shorterLength;
if(lhc.numberOfElements > rhc.numberOfElements)
{
shorterLength = rhc.numberOfElements;
}
else
{
shorterLength = lhc.numberOfElements;
}
//Vector *vector = new Vector(shorterLength, true);
Vector vector;
for(int i = 0; i<shorterLength; i++)
{
vector.container.push_back(lhc.container[i]+ rhc.container[i]);
}
return vector;
}
在main.cpp中。我无法在向量实例上调用+运算符,出现“无效运算符到二进制表达式向量*向量*”错误
您正在尝试添加两个指针。如果出于某种原因,您真的想使用
new
,那么您需要取消对指针的引用
c = *a + *b;
但几乎可以肯定的是,你最好使用物品
Vector a(10, false);
Vector b(5, false);
Vector c = a + b;
然后决定重载运算符是成员(声明时)还是非成员(定义时),并使声明和定义匹配。首先,有两个重载的
运算符+
其次,您正在指针上使用运算符+
,无法添加指针
c = a + b; <<<< Adding pointers doesn't make sense.
运算符既有成员版本,也有非成员版本。除此之外,您正在尝试添加指向向量的指针。
new
:使用向量
有什么特殊原因吗?
Vector a(10, false);
Vector b(5, false);
Vector c = a + b;
c = a + b; <<<< Adding pointers doesn't make sense.
Vector a(10, false);
Vector b((5, false);
Vector c = a + b;