Программа C ++ для обмена двух членов с помощью функции Friend
Предварительное условие: функция дружбы
ДЕЛО 1:
Учитывая два числа a и b, поменяйте местами эти два числа с помощью дружественной функции C ++.
Примеры:
Ввод: a = 5, b = 9 Выход: a = 9, b = 5 Ввод: a = 4, b = 6 Выход: a = 6, b = 4
Подход:
Создайте класс Swap, объявите в нем три переменные, то есть a, b и temp, и создайте конструктор для входов. Объявите в нем функцию друга. Определите функцию друга вне области действия класса, приняв аргументы как вызов по ссылке для передачи копии объекта Swap. Выполните операцию обмена с переменными Swap.
C ++
// C++ Program to swap two numbers using friend function #include <iostream> using namespace std; class Swap { // Declare the variables of Swap Class int temp, a, b; public : // Define the parameterized constructor, for inputs Swap( int a, int b) { this ->a = a; this ->b = b; } // Declare the friend function to swap, take arguments // as call by reference void friend swap(Swap&); }; // Define the swap function outside class scope void swap(Swap& s1) { // Call by reference is used to passed object copy to // the function cout << "
Before Swapping: " << s1.a << " " << s1.b; // Swap operations with Swap Class variables s1.temp = s1.a; s1.a = s1.b; s1.b = s1.temp; cout << "
After Swapping: " << s1.a << " " << s1.b; } // Driver Code int main() { // Declare and Initialize the Swap object Swap s(4, 6); swap(s); return 0; } |
Перед обменом: 4 6 После обмена: 6 4
СЛУЧАЙ 2:
Учитывая два объекта s1 и s2 класса, поменяйте местами элементы данных этих двух объектов с помощью дружественной функции C ++.
Примеры:
Ввод: a = 6, b = 10 Выход: a = 10, b = 6 Ввод: a = 4, b = 6 Выход: a = 6, b = 4
Подход:
Создайте класс Swap, объявите в нем одну переменную, т.е. num, и создайте конструктор для входов. Объявите в нем функцию друга. Определите функцию друга вне области действия класса, приняв аргументы как вызов по ссылке для передачи копии объекта Swap. Выполните операцию обмена.
C ++
//C++ Program to swap data members of two objects of a class using friend function. #include <iostream> using namespace std; class Swap { // Declare the variable of Swap Class int num; public : // Define the parameterized constructor, for input. Swap( int num) { this ->num = num; } // Declare the friend function to swap, take arguments // as call by reference void friend swap(Swap&, Swap&); }; // Define the swap function outside class scope void swap(Swap& s1, Swap& s2) { // declare a temporary variable. int temp; // Call by reference is used to passed object copy to // the function cout << "
Before Swapping: " << s1.num << " " << s2.num; // Swap operations with objects of class Swap temp = s1.num; s1.num = s2.num; s2.num = temp; cout << "
After Swapping: " << s1.num << " " << s2.num; } // Driver Code int main() { // Declare and Initialize the objects of Swap class Swap s1(6), s2(10); swap(s1,s2); return 0; } |
Перед обменом: 6 10 После обмена: 10 6