如何从操作员函数返回动态对象
How to return dynamic object from operator function?
我对此感到非常困惑。如何从操作员函数返回动态分配的对象?考虑以下示例:
#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的评论。因此,我希望我说服您返回对象而不是指针。
相关文章:
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 返回不停止函数,递归函数问题?(编程练习,动态规划,Levenshtein 回溯)
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- 动态数组传递给 main 中用随机值填充的函数,返回值3221226356
- 函数返回动态强制转换的指针,返回指针,就好像它根本没有被转换一样
- 静态分配和动态分配返回不同的答案
- 动态调用具有不同返回类型的相同命名函数
- 在存储库中,筛选器函数返回动态向量或其他存储库
- C++返回数组而不进行动态内存分配?
- C++ 返回具有最小硬币的数组/向量以获得价值动态规划
- C++ 如何从函数返回动态分配的数组
- 动态指针引用数组由三元运算符返回值,但有异常
- 动态使用返回的数组,如何释放其内存
- 如何让C++课"return"有能力?(或用户定义类型的返回动态)
- 如何从操作员函数返回动态对象
- 如何在没有指针的情况下返回动态结构
- 从函数返回动态数组后将其删除
- 无法从函数返回动态字符串
- 如何返回动态分配的数组
- 如何从运算符函数返回动态对象