如何从操作符函数返回动态对象?

如何从操作符函数返回动态对象?

问题描述:

我很困惑这个。如何从操作符函数返回动态分配的对象?
考虑下面的例子:

I am quite confused about this. How to return a dynamically allocated object from operator function? Consider following example:

#include "stdafx.h"
#include <iostream>
#include "vld.h"
using std::cout;
class Point
{
    public:
    Point(int x,int y) : a(x),b(y)
    { }
    Point()
    { }
    Point operator + (Point p)
    {
        Point* temp=new Point();
        temp->a=a+p.a;
        temp->b=b+p.b;
        Point p1(*temp);  // construct p1 from temp
        delete temp;      // deallocate temp
        return p1;
    }
    void show()
    {
        cout<<a<<' '<<b<<'\n';
    }
    private:
        int a,b;
};
int main()
{
    Point* p1=new Point(3,6);
    Point* p2=new Point(3,6);
    Point* p3=new Point();
    *p3=*p2+*p1;
    p3->show();
    VLDEnable();
    delete p1;
    delete p2;
    delete p3;
    VLDReportLeaks();
    system("pause");
}

我可以写这个程序没有额外的对象p1在这种情况下在重载的​​operator +功能?如何直接返回temp?

Can I write this program without extra object p1 in this case in overloaded operator + function? How Can I directly return temp?

您的帮助将非常感激。

请帮助我。 p>

Please help me.

Java语法和C ++之间有点混淆。在C ++中,除非你想要动态分配对象(在堆上),否则不需要 new 。只需使用

You are a bit confused between Java syntax and C++. In C++, there is no need for new unless you want your objects to be dynamically allocated (on the heap). Just use

Point temp; // define the variable
// process it
return temp;

这样,你的本地对象将被创建在堆栈上,你不必

In this way, your local objects will be created on the stack, and you won't have to care about forgetting to delete them etc.

运算符+ $>返回指针

Point* operator + (Point p) 
{ 
    Point* tmp = new Point;
    // process
    return tmp; // return the pointer to the dynamically-allocated object
}

code> operator + ,因为你不能链接它,即 a + b + c
这是因为 a + b 返回一个指针,然后 a + b + c 尝试调用 operator + 在一个指针上,没有定义。此外,还有更严重的问题,如在构建临时对象时分配内存泄漏,请参阅下面的@ Barry的注释。所以我希望我已经说服你返回的对象,而不是一个指针。

It actually breaks the operator+, since you won't be able to chain it, i.e. a+b+c won't work anymore. That's because a + b returns a pointer, then a + b + c tries invoking operator+ on a pointer, for which is not defined. Also, there are more serious issues, like leaking memory during the construction of your temporary objects in assignments, see @Barry's comment below. So I hope I have convinced you to return the object and not a pointer to it.