C ++简单重载operator + Not Compiling

时间:2014-03-19 05:25:08

标签: c++ operator-overloading

我有一个简单的向量类,我试图重载运算符+来添加向量。当它没有在我的主程序中工作时,我创建了一个新项目并将其剥离到最低限度,但它仍然无法正常工作。

裸露的最低代码:

的main.cpp

#include "vector3f.h"

int main()
{
    Vector3f* a = new Vector3f();
    Vector3f* b = new Vector3f();
    Vector3f* c = a + b;
}

vector.h

#ifndef __VECTOR3F_H__
#define __VECTOR3F_H__

class Vector3f
{
public:
    float x;
    float y;
    float z;

    Vector3f();
    Vector3f(float x, float y, float z);
    ~Vector3f();

    Vector3f operator+(const Vector3f& rhs);
}; 

#endif

vector.cpp

#include "vector3f.h"

Vector3f::Vector3f()
{
    x = 0;
    y = 0;
    z = 0;
}

Vector3f::Vector3f(float x, float y, float z)
{
    this->x = x;
    this->y = y;
    this->z = z;
}

Vector3f::~Vector3f()
{

}

Vector3f Vector3f::operator+(const Vector3f& rhs)
{
    return Vector3f(x + rhs.x, y + rhs.y, z + rhs.z);
}

这是编译错误:

main.cpp: In function 'int main()':
main.cpp:7: error: invalid operands of types 'Vector3f*' and 'Vector3f*' to binary 'operator+'

main.cpp第7行是Vector3f* c = a + b;

所以我的问题,正如Stack Overflow所预料的那样:我做错了什么?

旁注:我有一个非常蹩脚的IDE,问题可能是错误的编译器,但我不希望情况如此。

感谢任何帮助。在此先感谢!!

4 个答案:

答案 0 :(得分:3)

您动态分配了向量,并且没有为指针定义+运算符到向量。

所以你需要改变:

 Vector3f* a = new Vector3f();
 Vector3f* b = new Vector3f();
 //... assigning of and b
 Vector3f* c = a + b;

Vector3f* a = new Vector3f();
Vector3f* b = new Vector3f();
Vector3f* c = new Vector3f();
*c = *a + *b;

答案 1 :(得分:2)

我很惊讶这个没有被说过,但你为什么要使用指针呢?

Vector3f a;
Vector3f b;
Vector3f c = a + b;

不再尝试添加指针。没有更尴尬的语法。没有更多的内存泄漏。

除此之外,还有其他一些你应该改变的事情:

  • __VECTOR3F_H__reserved identifier
  • 您应该习惯使用constructor initializer lists: x(0), y(0), z(0): x(x), y(y), z(z)),而不是在数据成员已经初始化后分配给他们。
  • 你不需要在这里使用析构函数,因为将为你提供一个析构函数。
  • operator+ should be implemented使用operator+=,您还应该提供。

答案 2 :(得分:1)

试试这个,

 Vector3f c = *a + *b;

现在这将使您的操作员重载,这是一个指针添加

答案 3 :(得分:1)

您重载的对象不是对象指针。使用此

Vector3f c = (*a) + (*b);