为什么使用函数会出错

Why does using a function give me an error?

本文关键字:出错 函数 为什么      更新时间:2023-10-16

如果直接传入一个变量,它可以正常工作,但当我使用一个只返回变量的函数时,它就会停止工作。为什么会发生这种情况?

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
Point ap() const { ... }

ap按值返回,由于您没有将函数调用存储在任何位置,因此执行以下操作:

 f(e.ap()); 

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

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

  • 通过常量引用返回Point::ap,即

     Point const& ap() { ... }
    
  • 使f通过const&、值或通过右值引用Point&& 获取其参数

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

     Point p = e.ap();
     f(p);
    

ap返回的Point是临时的。为了将临时参数作为参数传递,函数需要按值、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