📜  C++中友元函数和虚函数的区别

📅  最后修改于: 2021-09-13 01:59:50             🧑  作者: Mango

友元类可以访问其声明为友元的其他类的私有成员和受保护成员。允许特定类访问其他类的私有成员有时很有用。很可能,友元函数是在类范围之外声明的函数。这个函数可以像普通函数一样被调用,并包含 object/s 作为参数。它主要用于为 I/O 重载 <>。它通常可以访问它是朋友的类的任何成员。

插图:

class GFG  
{ 
 private: 
 {  
 Public: 
 {  
 friend void check();  
 }
  
void check();  

现在要介绍的第二个函数是虚函数。因此,虚函数基本上是在基类中声明的类的成员函数。其中,virtual 关键字用于使基类 Virtual 的成员函数。它还支持编译时和运行时的多态性。它还允许派生类简单地替换由基类提供或给出的实现。

插图:

class GFG  
{  
Public:  
          Virtual return_type function_name(arguments)  
         {  
         …..  
         }  
}:  
   class A  
  {  

到目前为止,我们已经清楚地讨论了友元函数和虚函数,现在让我们看看它们之间的主要区别,甚至可以很好地掌握它们。

Friend Function 

Virtual Function 

It is non-member functions that usually have private access to class representation.   It is a base class function that can be overridden by a derived class.  
It is used to access private and protected classes.  It is used to ensure that the correct function is called for an object no matter what expression is used to make a function class.
It is declared outside the class scope. It is declared using the ‘friend’ keyword. It is declared within the base class and is usually redefined by a derived class. It is declared using a ‘virtual‘ keyword.
It is generally used to give non-member function access to hidden members of a class.   It is generally required to tell the compiler to execute dynamic linkage of late binding on function.  
They support sharing information of class that was previously hidden, provides method of escaping data hiding restrictions of C++, can access members without inheriting class, etc.   They support object-oriented programming, ensures that function is overridden, can be friend of other function, etc.  
It can access private members of the class even while not being a member of that class.   It is used so that polymorphism can work. 
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程