朋友类别可以访问被声明为朋友的其他类别的私有成员和受保护成员。有时允许特定的类访问其他类的私有成员有时很有用。朋友函数很可能是在类范围之外声明的函数。该函数可以像普通函数一样被调用,并包含对象作为参数。它主要用于I / O重载<<和>>。它通常可以访问与其成为好友的类的任何成员。
插图:
class GFG
{
private:
{
Public:
{
friend void check();
}
void check();
现在,第二个函数是虚拟函数。因此,虚函数基本上是在基类中声明的类的成员函数。在此,虚拟关键字用于使基类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等的更多准备工作,请参阅“完整面试准备课程” 。