[英]Returning a global object from a function in C++
I'm trying to make a function that returns one of the 3 global objects I have depending on the parameter received, but I'm getting the following error: invalid initialization of non-const reference of type 'block&' from a temporary of type 'block'. 我试图使函数返回一个我拥有的3个全局对象中的一个,具体取决于收到的参数,但是出现以下错误:从临时类型的非常量引用'block&'的无效初始化'块'。
I'm not very familiar with C++ and references, but I tried different things and nothing seems to work. 我对C ++和引用不是很熟悉,但是我尝试了不同的方法,但似乎没有任何效果。 What would be the correct way to do this?
正确的方法是什么?
Of course what I want is that the actual chosen global object is passed from getBlock to modifyBlock so that it is modified; 当然,我想要的是将实际选择的全局对象从getBlock传递到ModifyBlock以便对其进行修改; at the end the program should print "IT WORKS!".
最后,程序应打印“ IT WORKS!”。
#include <string>
#include <iostream>
using namespace std;
class block
{
public:
string blockId;
block (string id);
};
block::block(string id)
{
blockId=id;
}
block A = block("A");
block B = block("B");
block getBlock (string b)
{
if(A.blockId==b)
return A;
else return B;
}
block modifyBlock (block &x)
{
x.blockId="IT WORKS!";
}
int main ()
{
string b;
cout<<"Which block? ";
cin>>b;
modifyBlock(getBlock(b));
cout<<endl<<getBlock(b).blockId;
}
This function signature: 该函数签名:
block getBlock (string b)
means you are returning a block
object by value . 表示您正在按值返回一个
block
对象。 You return a copy of one of the global block
objects. 您返回一个全局
block
对象的副本。 When used like this: 当这样使用时:
modifyBlock(getBlock(b));
it fails, because the argument to the function is a temporary, and that cannot bind to a non-const lvalue reference. 之所以失败,是因为该函数的参数是临时参数,并且不能绑定到非常量左值引用。 It looks like you want to return a reference (
block&
) here: 看来您想在此处返回引用(
block&
):
block& getBlock (string b)
{ // ^
return A.blockId == b ? A : B;
}
Simply modify the function 只需修改功能
block getBlock (string b)
{
if(A.blockId==b)
return A;
else return B;
}
the following way 以下方式
block & getBlock( const string &b )
{
if(A.blockId==b)
return A;
else return B;
}
You are going to change either object A or B not their copies are not you? 您将要更改对象A或B,不是它们的副本,不是吗?
As for the error then you are passing a temporary object returned by function getBlock to function modifyBlock. 对于错误,您正在将函数getBlock返回的临时对象传递给函数ModifyBlock。 Temporary objects my be bound only with constant references.
临时对象只能与常量引用绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.