I’m having a slight bit of trouble implementing some simple operator overload (it’s for a short demo need example of topic). I currently have my code set up as follows:
That builds fine for me but when I try use it in one of my other classes e.g:
FString Ammo; Ammo << MyCharacter->Ammo;
I’m getting error "no operator ‘<<’ matches these operands, types are FString << int32 also if I try use the operator directly when creating FString it keeps saying a “;” is missing e.g:
FString Health << MyCharacter->Health;
Also I should note above I have code FString& operator<< this is from looking at the tutorial here I’ve also tried this setup with FString &operator<< which is the way it is shown for operator overloading in the C++ notes I’m working out of, neither works for me.
I have a .h and .cpp specifically for the operator over loading that’s where the first two snippets of code are respectively. And the .h for operator overloading is included in the .cpp file where I am trying to use the overloaded operator (third/fourth snippet).
You shouldn’t put operator overloads in .cpp files, just keep it in the .h
//some .h file that stores all your operators
FORCEINLINE FString& operator<<(FString &Str, const int32& Value)
{
Str += FString::FromInt(Value);
return Str;
}
and put in in a .h file that is included in every class that needs to use the operator
#UObject Static Function Library
An ideal place to put operators is in a .h file that is a static function library where you store all your core custom code, which is then included in all your major game class .h files.