为什么使用函数会出错
Why does using a function give me an error?
如果直接传入一个变量,它可以正常工作,但当我使用一个只返回变量的函数时,它就会停止工作。为什么会发生这种情况?
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
相关文章:
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了
- PrintWindow函数在notepad.exe中出错
- 使用运算符调用 void 函数时出错<set>
- 为 NewObjectA() 函数创建 jvalues 的参数数组时出错 - JNI Invocation API
- 在定义的函数中使用常量时出错
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 使用根/C++时出错:没有匹配的构造函数来初始化'TTree'
- Arduino IDE 中使用 strncmp 函数时出错
- 从DLL导出函数,LoadLibrary()需要用TEXT转换的字符串才能编译而不会出错
- 编译包含指向模板函数的指针的初始值设定项列表时,gcc 出错,但 clang 不出错
- 使用一个参数的模板函数时出错(适用于 2)
- 为什么 stl 字符串C++函数有时出错有时会出错?
- 使用类的构造函数时出错
- 在 c++ 的构造函数中分配对象向量时出错
- 为什么在函数参数前面添加 const 会出错?
- 调用析构函数时出错