在本文中,我们将讨论虚拟函数在C++的派生类和抽象基类的派生类中的行为。
考虑以下程序:
C++
// C++ program to illustrate the concept
// of Virtual Function
#include
using namespace std;
// Base Class
class Base {
public:
// Virtual Function
virtual void print()
{
cout << "Inside Base" << endl;
}
};
// Derived Class
class Derived : public Base {
};
// Driver Code
int main()
{
// Object of the derived class
Base* b2 = new Derived();
// Function Call to Base Class
b2->print();
return 0;
}
C++
// C++ program to illustrate the concept
// of virtual function
#include
using namespace std;
// Base Class
class Base {
public:
// Virtual Function
virtual void print() = 0;
};
// Derived Class
class Derived : public Base {
// Overriding of virtual function
void print()
{
cout << "Inside Derived"
<< endl;
}
};
// Driver Code
int main()
{
// Object of the derived class
Base* b2 = new Derived();
// Function Call to Base Class
b2->print();
return 0;
}
C++
// C++ program to illustrate the concept
// of virtual function
#include
using namespace std;
// Base Class
class Base {
public:
// Virtual Function
virtual void print() = 0;
};
// Derived Class
class Derived : public Base {
};
// Driver Code
int main()
{
// Object of the derived class
Base* b2 = new Derived();
// Function Call to Base Class
b2->print();
return 0;
}
输出:
Inside Base
说明:当声明基类的指针指向派生类的对象时,只有在需要在派生类中重写该函数时,才在基中将函数声明为虚函数。如果在基类中将该函数声明为虚函数,则不建议在派生类中重写该函数,它仍将调用该虚函数并执行该虚函数。
仅当需要运行时多态性并在派生类中重写基类的函数时, virtual关键字才有效。如果使用了虚拟关键字,并且不建议在派生类中重写该函数,则虚拟关键字是没有用的。此属性对Abstract Base类不成立,因为在Base类中也没有函数体。下面是说明相同内容的程序:
程序1:
C++
// C++ program to illustrate the concept
// of virtual function
#include
using namespace std;
// Base Class
class Base {
public:
// Virtual Function
virtual void print() = 0;
};
// Derived Class
class Derived : public Base {
// Overriding of virtual function
void print()
{
cout << "Inside Derived"
<< endl;
}
};
// Driver Code
int main()
{
// Object of the derived class
Base* b2 = new Derived();
// Function Call to Base Class
b2->print();
return 0;
}
输出:
Inside Derived
程式2:
C++
// C++ program to illustrate the concept
// of virtual function
#include
using namespace std;
// Base Class
class Base {
public:
// Virtual Function
virtual void print() = 0;
};
// Derived Class
class Derived : public Base {
};
// Driver Code
int main()
{
// Object of the derived class
Base* b2 = new Derived();
// Function Call to Base Class
b2->print();
return 0;
}
输出:
说明:如果比较以上两个程序,则该函数被抽象类覆盖时,则virtual关键字将按预期的方式工作。但是在以上程序中,该函数未在基类内部被覆盖,并且该函数未在基类中定义,因此导致编译错误。
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。