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

How to return dynamic object from operator function?

本文关键字:返回 动态 对象 函数 操作员      更新时间:2023-10-16

我对此感到非常困惑。如何从操作员函数返回动态分配的对象?考虑以下示例:

#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?我如何直接返回温度?

您的帮助将不胜感激。

请帮助我。

您在Java语法和C 之间有些混淆。在C 中,不需要new,除非您希望将对象动态分配(在堆上)。只需使用

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

以这种方式,您的本地对象将在堆栈上创建,您将不必忘记忘记delete等。

operator+返回指针是错误的

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

它实际上会打破operator+,因为您将无法链接它,即a+b+c将无法正常工作。这是因为a + b返回指针,然后a + b + c尝试在指针上调用operator+,而该指针未定义。此外,还有更严重的问题,例如在作业中构建临时对象期间的内存泄漏,请参见 @barry的评论。因此,我希望我说服您返回对象而不是指针。