如何从运算符函数 return 动态对象?
How to return dynamic object from operator function?
我对此很困惑。如何从运算符函数 return 动态分配对象?
考虑以下示例:
#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 的程序吗?我怎样才能直接return temp?
非常感谢您的帮助。
请帮帮我
您对 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
return 是一个指针,然后 a + b + c
尝试在一个未定义的指针上调用 operator+
。此外,还有更严重的问题,例如在分配中构造临时对象期间内存泄漏,请参阅下面的@Barry 评论。所以我希望我已经说服您 return 对象而不是指向它的指针。
我对此很困惑。如何从运算符函数 return 动态分配对象? 考虑以下示例:
#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 的程序吗?我怎样才能直接return temp?
非常感谢您的帮助。
请帮帮我
您对 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
return 是一个指针,然后 a + b + c
尝试在一个未定义的指针上调用 operator+
。此外,还有更严重的问题,例如在分配中构造临时对象期间内存泄漏,请参阅下面的@Barry 评论。所以我希望我已经说服您 return 对象而不是指向它的指针。