-4

如果直接传入一个变量,它工作得很好,但是当我使用一个只返回变量的函数时,它就停止工作了。为什么会这样?

struct Edge {
    Point ap() const { return set[a]; }

    Point *set;
    int a;
}

function f(Point &p) {}

Edge e;

f(e.ap()); // Error: No matching function call to 'f'
f(e.set[e.a]); // Works fine

Point p = e.ap();
f(p); // Works fine
4

2 回答 2

3
Point ap() const { ... }

ap按值返回,并且由于您没有将函数调用存储在任何地方,请执行以下操作:

 f(e.ap()); 

返回一个临时对象到f,它不能绑定到一个Point&类型。

你有很多选择,你可以...

  • 通过constPoint::ap引用返回,即

     Point const& ap() { ... }
    
  • 通过、 按值或通过 rvalue-reference获取f其参数const&Point&&

  • 将函数调用的结果存储在变量中:

     Point p = e.ap();
     f(p);
    
于 2013-07-04T20:55:07.770 回答
2

Point返回的人是ap临时的。为了将临时参数作为参数传递,函数需要按值、const引用或右值引用来获取参数。

void function f(Point p) {}         // By value
void function f(const Point& p) {}  // By const reference
void function f(Point &&p) {}       // By rvalue reference
于 2013-07-04T20:56:27.240 回答