C++ Builder: Write your own ClassesIn C++, a class is declared with the "class" keyword, a name, and (optionally) an inheritance.
Here’s an example: class TStudent : public TObject { private: String FName; float FGrade; public: void SetName(String s) { FName = s; }; void SetGrade(float x) { FGrade = x; }; String GetName() { return FName; }; float GetGrade() { return FGrade; }; };
This class has private data and uses public setter and getter methods to access the internal (private) data. TStudent *Student = new TStudent; Student->SetName("Jones, Jenny"); Student->SetGrade(78.5);
PropertiesProperties allow you to write cleaner code. They also let you perform some specific action when the property is written to or read. class TStudent : public TObject { private: String FName; float FGrade; void SetName(String s) { FName = s; }; void SetGrade(float x) { FGrade = x; }; public: __property String Name = { read = FName, write = SetName }; __property float Grade = { read = FGrade, write = SetGrade }; }; This allows us to directly read from and write to these properties, thus write stuff like: Example projectHere's a simple project to illustrate our class TStudent. Place the declaration of class TStudent before the existing declaration of the form, so it can be accessed from anywhere in the unit. The complete code is as follows: class TStudent : public TObject { // inherits from TObject private: String FName; float FGrade; void SetName(String s) { FName = s; }; void SetGrade(float x) { FGrade = x; }; public: __property String Name = { read = FName, write = SetName }; __property float Grade = { read = FGrade, write = SetGrade }; }; TForm1 *Form1; __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } void __fastcall TForm1::Button1Click(TObject *Sender) { TStu *Student = new TStudent; Student->Name = "Jones, Jenny"; Student->Grade = 78.5; Label1->Caption = Student1->Name + ": " + FloatToStr(Student1->Grade); delete Student; } |
|