📜  C ++程序使用Friend 函数交换两个成员

📅  最后修改于: 2021-05-31 23:38:02             🧑  作者: Mango

先决条件:朋友函数

情况1:
给定两个数字a和b,请使用C++的朋友函数交换这两个数字。

例子:

Input : a = 5, b = 9
Output : a = 9, b = 5

Input : a = 4, b = 6
Output : a= 6, b = 4

方法:
创建一个Swap类,在其中声明三个变量,即a,b和temp,并为输入创建一个构造函数。在其中声明一个朋友函数。通过将参数作为通过引用的调用来传递交换对象的副本,从而在类范围之外定义Friendly函数。使用交换变量执行交换操作。

// C++ Program to swap two numbers using friend function
#include 
  
using namespace std;
  
class Swap {
  
    // Declare the variables of Swap Class
    int temp, a, b;
  
public:
  
    // Define the parametrized 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
    friend void 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 << "\nBefore Swapping: " << s1.a << " " << s1.b;
  
    // Swap operations with Swap Class variables
    s1.temp = s1.a;
    s1.a = s1.b;
    s1.b = s1.temp;
    cout << "\nAfter Swapping: " << s1.a << " " << s1.b;
}
  
// Driver Code
int main()
{
    // Declare and Initialize the Swap object
    Swap s(4, 6);
    swap(s);
    return 0;
}
输出:
Before Swapping: 4 6
After Swapping: 6 4

情况2:
给定一个类的两个对象s1和s2,使用C++的友好函数交换这两个对象的数据成员。

例子:

Input : a = 6, b = 10
Output : a = 10, b = 6

Input : a = 4, b = 6
Output : a= 6, b = 4

方法:
创建一个类Swap,在其中声明一个变量,即num,并为输入创建一个构造函数。在其中声明一个朋友函数。通过将参数作为通过引用的调用来传递交换对象的副本,从而在类范围之外定义Friendly函数。执行交换操作。

//C++ Program to swap data members of two objects of a class using friend function.
#include  
    
using namespace std; 
    
class Swap { 
    
    // Declare the variable of Swap Class 
    int num;
    
public: 
    
    // Define the parametrized constructor, for input. 
    Swap(int num) 
    { 
        this->num = num; 
    } 
    
    // Declare the friend function to swap, take arguments  
    // as call by reference 
    friend void 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 << "\nBefore Swapping: " << s1.num << " " << s2.num; 
    
    // Swap operations with objects of class Swap
    temp = s1.num; 
    s1.num = s2.num; 
    s2.num = temp; 
    cout << "\nAfter 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; 
} 
输出:
Before Swapping: 6 10
After Swapping: 10 6
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”