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'.
I'm not very familiar with C++ and references, but I tried different things and nothing seems to work. 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; at the end the program should print "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 . You return a copy of one of the global block
objects. 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& 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?
As for the error then you are passing a temporary object returned by function getBlock to function modifyBlock. Temporary objects my be bound only with constant references.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.