Примеры выполнения перегрузки функции и использования шаблона функции

Перегрузка функции swap

#include "stdafx.h"

using namespace std;

void swap(int &x, int &y);

void swap(float&x, float &y);

void swap(double &x, double &y);

main()

{

int x=2,y=3;

swap(x,y);

float a=5.0,b=7.0;

swap(a,b);

double c=9.1,d=8.2;

swap(c,d);

cout << c <<' '<< d;

cin.get();

}

void swap(int &x, int &y)

{

int w=x;

x=y;

y=w;

}

void swap(float&x, float &y)

{

float w=x;

x=y;

y=w;

}

void swap(double &x, double &y)

{

double w=x;

x=y;

y=w;

}

Функция шаблон

#include "stdafx.h"

#include "iostream.h"

template<class T>

void swap(T &x,T &y);

int main()

{

int x=2,y=3;

swap(x,y);

float a=5.0,b=7.0;

swap(a,b);

double c=9.1,d=8.2;

swap(c,d);

cout << c <<' '<< d;

cin.get();

cout<<a<<' '<<b;

return 0;

}

template<class T>

void swap(T &x,T &y)

{T z=x;

x=y;

y=z;

}

Перегрузка бинарной операции(внешняя функция)== для структур данных.

#include "stdafx.h"

using namespace std;

struct data{int x;int y;};

int operator == (data z1,data z2);

main()

{ data l={1,2};

data m={1,2};

if (m==l)

cout<<"yes";

else

cout<<"no";

cin.get();

}

int operator ==(data z1,data z2)

{ if (z1.x==z2.x && z1.y==z2.y)

return 1;

return 0;

}


Понравилась статья? Добавь ее в закладку (CTRL+D) и не забудь поделиться с друзьями:  



double arrow
Сейчас читают про: