1. โครงสร้างคลาสอย่างง่าย
Ex1 ตัวอย่างคลาส Person อย่างง่าย#include <iostream>
#include <string>
using namespace std;
class Person {
public:
string PID;
string Fullname;
string Address;
};
int main(int argc, char** argv)
{
Person p;
p.PID = "001";
p.Fullname = "John Doe";
p.Address = "Bangkok";
cout << "PID : " << p.PID << endl;
cout << "Fullname : " << p.Fullname << endl;
cout << "Address : " << p.Address << endl;
system("pause");
return 0;
}
Result:
PID : 001
Fullname : John Doe
Address : Bangkok
2. การใช้ Getter/Setter เข้าถึงข้อมูล
Ex2 ตัวอย่างคลาส Person เพิ่ม method และใช้ Getter/Setter ในการเข้าถึงข้อมูล#include <iostream>
using namespace std;
class Person {
public:
/****** Setter and Getter ******/
void setPID (string PID) {
_PID = PID;
}
string getPID () {
return _PID;
}
void setFullname (string Fullname) {
_Fullname = Fullname;
}
string getFullname () {
return _Fullname;
}
void setAddress (string Address) {
_Address = Address;
}
string getAddress () {
return _Address;
}
/****** Methods ******/
void Speak(){
cout << "Person speak" << endl;
}
void Walk(){
cout << "Person walk" << endl;
}
private:
string _PID;
string _Fullname;
string _Address;
};
int main(int argc, char** argv)
{
Person p;
p.setPID("001");
p.setFullname("John Doe");
p.setAddress("Bangkok");
p.Speak();
p.Walk();
cout << "--------------------------------" << endl;
cout << "PID : " << p.getPID() << endl;
cout << "Fullname : " << p.getFullname() << endl;
cout << "Address : " << p.getAddress() << endl;
system("pause");
return 0;
}
Result:
Person speak
Person walk
--------------------------------
PID : 001
Fullname : John Doe
Address : Bangkok
Sign up here with your email
ConversionConversion EmoticonEmoticon