如果您不通过引用返回某些函数,在什么情况下会产生错误?
最佳答案
如果您不通过引用返回某些函数,在什么情况下会产生错误?
将答案限制在确切要求的范围内,
每当您希望函数的返回值充当l值并且不通过引用返回时,它将生成错误。
最常见的例子是operator []
(数组订阅运算符)超载,您必须按引用返回,以便在l.h.s上使用[]
或更正确地将其用作l值。
An example:
class Myclass
{
int i;
public:
/*Not returned by reference- gives error*/
int operator[](int idx){ return i;}
/*Returned by reference- gives no error*/
//int& operator[](int idx){ return i;}
};
int main()
{
Myclass obj;
obj[1]= 10;
return 0;
}
输出:
prog.cpp:在“ int main()”函数中:
prog.cpp:16:错误:需要左值作为赋值的左操作数
关于c++ - 按引用还是按值返回。 C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10379988/