5.1 Function Overloading
เราสามารถสร้าง function ที่มีชื่อซ้ำกันได้โดยมีอินพุตที่ต่างกัน
using namespace std;
class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(){
Vec2D A(3.0f, 4.0f),B(2.0f,1.0f),C,D;
cout<< "A = "<<A;
cout<< "B = "<<B;
D=C=A*10.0f + B*0.5f;
cout<< "C = "<< C;
cout<< "D = "<< D;
return 0;
}
output
5
500.263
Hello C++
5.2 Operator Overloading
คลาสอาจมีตัวกระทำที่เราสามารถกำหนดเองได้ เช่นเรามีคลาสที่ชื่อ Complex ที่เก็บจำนวนจินตภาพ โดยอาจจะมีตัวกระทำ +, - และ อื่นๆ รูปแแบการเขียนโปรแกรม คือ
type classname::operator+(arg-list) { // operations }
ตัวอย่างการทำ operator overloading
#include <iostream>
#include <math.h>
using namespace std;
class Vec2D{
private:
float x,y;
public:
Vec2D(){ x = 0.0f; y = 0.0f;}
Vec2D(float _x, float _y){
x = _x;
y = _y;
}
Vec2D operator - (Vec2D B){//subtraction
Vec2D temp;
temp.x = x - B.x;
temp.y = y - B.y;
return temp;
}
Vec2D operator + (Vec2D B){//addition
Vec2D temp;
temp.x = x + B.x;
temp.y = y + B.y;
return temp;
}
Vec2D operator = (Vec2D B){
x = B.x;
y = B.y;
return *this;
}
Vec2D operator * (float k){
Vec2D temp;
temp.x = k * x;
temp.y = k * y;
return temp;
}
friend ostream& operator<<(ostream& out, const Vec2D& A);
};
ostream& operator<<(ostream& out, const Vec2D& A) {
return out << "( "<<A.x << ", "<< A.y << " )\n";
}
int main(){
Vec2D A(3.0f, 4.0f),B(2.0f,1.0f),C;
cout<< "A = "<<A;
cout<< "B = "<<B;
cout<< "A * 10 + B * 0.5 = "<< A*10.0f + B*0.5f;
return 0;
}
output
Running /home/ubuntu/workspace/code425_operator.cpp
A = ( 3, 4 )
B = ( 2, 1 )
C = ( 31, 40.5 )
D = ( 31, 40.5 )