当函数需要返回对象时,通常有两种写法,一种是直接在return语句中返回一个对象,一种是先构造好一个对象,然后在return中将其返回。以下代码为例:
#include <iostream>
#include <string>
using namespace std;
struct Node{
string name;
int x, y;
Node(string na = "", int xx = 0, int yy = 0) : name(na), x(xx), y(yy) {
cout << name << " " << "constructed" << endl;
cout << "address " << this << endl;
}
Node(const Node& n) : name(n.name), x(n.x), y(n.y) {}
~Node() {cout << name << " " << "deconstructed" << endl; }
};
Node add_1(const Node& a, const Node& b){
return Node(string("temp object"), a.x + b.x, a.y + b.y);
}
Node add_2(const Node& a, const Node& b){
Node local(strin