简体   繁体   English

何时通过引用传递并返回c ++中的函数

[英]when to pass and return by reference to a function in c++

first I made a complex class in c++ which had two member datas -real and imaginary.(of the form a+ib). 首先,我在c ++中创建了一个复杂的类,它有两个成员数据--real和imaginary。(形式为a + ib)。 when I tried to overload << operator for complex class object as follows- 当我试图为复杂类对象重载<<运算符如下 -

friend ostream operator<<(ostream ,complex );  in .h file

ostream operator <<(ostream o,complex c){

    o<<"real part"<<c.real;
    o<<"imaginary part<<c.imaginary;
    return o;

}  

in .cpp file, it does not work and rather opens an ios_base file and shows an error there. 在.cpp文件中,它不起作用,而是打开一个ios_base文件并在那里显示错误。 but the same code overloads << perfectly when i pass by reference and return by reference as follows- 但是当我通过引用传递并通过引用返回如下时,相同的代码会完美地重载<<

ostream& operator <<(ostream& o,complex& c)
{



      //same as before
};

i dont understand how passing and returning by reference helps? 我不明白通过引用传递和返回有什么帮助?

std::ostream is not-copyable type type. std :: ostream不可复制的类型。 You cannot do copy of o , so you must receive it by reference and return it by reference. 您不能复制o ,因此您必须通过引用收到它并通过引用将其返回。

The rule for using a reference vs. not using a reference is simple: if you want to use the same object as in the caller, pass it by reference; 使用引用与不使用引用的规则很简单:如果要使用与调用者中相同的对象,请通过引用传递它; if you want to make a copy of the object being passed, do not use reference. 如果要复制正在传递的对象,请不要使用引用。

In some cases you can pass an object only by reference. 在某些情况下,您只能通过引用传递对象。 Specifically, when it is incorrect to copy an object, designers of its class can prohibit copying. 具体来说,当复制对象不正确时,其类的设计者可以禁止复制。 Objects that represent input/output and synchronization resources are often non-copyable, meaning that you must pass them by reference or by pointer. 表示输入/输出和同步资源的对象通常是不可复制的,这意味着您必须通过引用或指针传递它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM