OpOverloads (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example shows how to write and invoke class or record operator overloads. The strings added to the TMemo describe the code being executed and the operators that are actually used.

This example is being referenced from specific records like System.Variant that have many operator overloads, but the example shows you how to implement operator overloads in your own records.

Code

struct DECLSPEC_DRECORD MyStruct
{
  int payload;
  static MyStruct __fastcall _op_Addition(const MyStruct &Left, const MyStruct &Right);
  static MyStruct __fastcall _op_Modulus(const MyStruct &Left, const MyStruct &Right);
};

MyStruct __fastcall MyStruct::_op_Addition(const MyStruct &Left, const MyStruct &Right)
{
  MyStruct retStruct;
  Form1->Memo1->Lines->Add("_op_Addition(const MyStruct &Left, const MyStruct &Right)");
  retStruct.payload = Left.payload + Right.payload;
  return retStruct;
}

inline MyStruct operator+(const MyStruct &Left, const MyStruct &Right)
{
  return MyStruct::_op_Addition(Left, Right);
 }

MyStruct __fastcall MyStruct::_op_Modulus(const MyStruct &Left, const MyStruct &Right)
{
  MyStruct retStruct;
  Form1->Memo1->Lines->Add("_op_Modulus(const MyStruct &Left, const MyStruct &Right)");
  retStruct.payload = Left.payload % Right.payload;
  return retStruct;
}

inline MyStruct operator%(const MyStruct &Left, const MyStruct &Right)
{
  return MyStruct::_op_Modulus(Left, Right);
}


//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
  MyStruct a, b;
  a.payload = 4;
  Memo1->Lines->Add("a.payload = " + IntToStr(a.payload));
  b.payload = 5;
  Memo1->Lines->Add("b.payload = " + IntToStr(b.payload));
  Memo1->Lines->Add("Testing: b = b + a;");
  b = b + a;
  Memo1->Lines->Add("b.payload = " + IntToStr(b.payload));
  Memo1->Lines->Add("Testing: b = b % a;");
  b = b % a;
  Memo1->Lines->Add("b.payload = " + IntToStr(b.payload));
}

Uses

Personal tools
Assistance