Operator Overloading

Hey Guys,

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:

Header:

friend FString& operator<<(FString &Str, const int32& Value);

Cpp:

FORCEINLINE	FString& operator<<(FString &Str, const int32& Value)
{
	Str += FString::FromInt(Value);
	return Str;
}

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.

In which header have you added the declaration? And have you included that header in the part of your project where you are trying to use it?

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).

#Solusion

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.

#Wiki on Static Function Libraries

:slight_smile:

RAma