Just a quick question.
I've written some code that returns a custom class Command, and the code I've written seems to work fine. I was wondering if there are any reasons that I shouldn't be doing it this way. It's something like this:
Command Behavior::getCommand ()
{
char input = 'x';
return Command (input, -1, -1);
}
Anyway, I read that constructors aren't mean开发者_如何学Got to have a return value, but this works in g++.
Thanks for any advice,
Rhys
The constructor itself doesn't have a return value. What this does is constructs a temporary Command
object and returns the constructed objet to the caller. It's effectively the same as if you said:
Command temp(input, -1, -1);
return temp;
It will work on any C++ compiler.
getCommand
isn't a constructor. The above is perfectly valid, and also generally efficient, due to thre return-value optimisation (RVO), which (I think) wouldn't apply if you instantiated a local variable and returned that.
The constructor doesn't have a return value; you're explicitly constructing a temporary instance of the class, and returning that. There's nothing wrong with this, other than it will make a copy.
If you want to avoid the copy, you have a few options, one of which is to have an out parameter which is a Command*
and use new and delete.
You don't have a constructor with a return value.
Command::Command(char, int, int)
is your constructor.
You have a method which returns an object, which is perfectly normal.
精彩评论