函数重载
#include <iostream>
using namespace std;
int add(int a, int b)
{
cout << "调用整型类型.\n";
return a + b;
}
int add(char a, char b)
{
cout << "调用字符型类型.\n";
return a + b;
}
double add(double a, double b)
{
cout << "调用双精度型类型.\n";
return a + b;
}
int main()
{
cout << "两数相加的结果是:" << add(25, 82) << endl << endl;
cout << "两数相加的结果是:" << add('A', 'B') << endl << endl;
cout << "两数相加的结果是:" << add(89.9, 78.1) << endl << endl;
return 0;
}
运算符重载
#include <iostream>
using namespace std;
class Box
{
public:
Box()
{
l = 0;
b = 0;
h = 0;
}
void setl(double length)
{
l = length;
}
void setb(double breadth)
{
b = breadth;
}
void seth(double hight)
{
h = hight;
}
double getv(void)
{
return l * b * h;
}
Box operator+(const Box& b)
{
Box box;
box.l = this->l + b.l;
box.b = this->b + b.b;
box.h = this->h + b.h;
return box;
}
private:
double l;
double b;
double h;
};
int main()
{
Box box1;
Box box2;
Box box3;
double dv = 0.0;
box1.setl(2.0);
box1.setb(3.0);
box1.seth(4.0);
box2.setl(5.0);
box2.setb(6.0);
box2.seth(7.0);
dv = box1.getv();
cout << "box1对象的体积为:" << dv << endl << endl;
dv = box2.getv();
cout << "box2对象的体积为:" << dv << endl << endl;
box3 = box1 + box2;
dv = box3.getv();
cout << "box3对象的体积为:" << dv << endl << endl;
return 0;
}
#include <iostream>
using namespace std;
class CTestSS
{
public:
CTestSS() :i(0)
{
}
CTestSS operator++()
{
cout << "调用前置递增.\n";
CTestSS obj;
obj.i = ++i;
return obj;
}
CTestSS operator++(int)
{
cout << "调用后置递增.\n";
CTestSS obj;
obj.i = i++;
return obj;
}
void disp()
{
cout << "i=" << i << endl;
}
private:
int i;
};
int main()
{
CTestSS obj1, obj2;
cout << "输出结果1为:" << endl;
obj1.disp();
obj2.disp();
obj2 = ++obj1;
cout << "输出结果2为:" << endl;
obj1.disp();
obj2.disp();
obj2 = obj1++;
cout << "输出结果3为:" << endl;
obj1.disp();
obj2.disp();
return 0;
}
#include <iostream>
using namespace std;
class CTest
{
public:
CTest() :x(10)
{
}
CTest operator--()
{
cout << "调用前置递减.\n";
CTest obj;
obj.x = --x;
return obj;
}
CTest operator--(int)
{
cout << "调用后置递减.\n";
CTest obj;
obj.x = x--;
return obj;
}
void disp()
{
cout << "x=" << x << endl;
}
private:
int x;
};
int main()
{
CTest obj1, obj2;
cout << "输出结果1为:" << endl;
obj1.disp();
obj2.disp();
obj2 = --obj1;
cout << "输出结果2为:" << endl;
obj1.disp();
obj2.disp();
obj2 = obj1--;
cout << "输出结果3为:" << endl;
obj1.disp();
obj2.disp();
return 0;
}