传递引用参数并返回引用

问题描述 投票:0回答:1

我一直在阅读有关运算符重载的内容,并且已经了解到如果从函数返回引用,则可以级联重载运算符。

我的问题是这个。为了返回引用,您是否需要传递对函数的引用,或者该值是否可以?

例如两者都有效吗?

ostream &operator<<(ostream output, string &label);

ostream &operator<<(ostream &output, string &label);

第一个也会返回对传递给函数的输出流参数的有效引用,还是需要传入输出流对象作为引用将其作为引用返回?

c++ operator-overloading pass-by-reference
1个回答
1
投票

你不能使用

std::ostream &operator<<(std::ostream output, std::string &label);

因为std::ostream没有复制构造函数。

即使std::ostream有一个拷贝构造函数,使用上面的接口也会导致以下问题。

Problem 1

返回对输入参数的引用将是一个问题。函数返回后,该对象将不会处于活动状态。因此,一旦函数返回,返回的引用将是悬空引用。使用悬空引用会导致未定义的行为。

Problem 2

这是假设的。

想象一下如果使用会发生什么:

std::ofstream outfile("myoutput.txt");
outfile << "A string.";

该调用将导致对象切片。你会失去对象的std::ofstream-ness。输出将在哪个函数中输入?它肯定不会去文件。


坚持

std::ostream &operator<<(std::ostream &output, std::string const& label);

PS是的,我确实将第二个参数的类型更改为const&

© www.soinside.com 2019 - 2024. All rights reserved.