我正在学习C++,我刚刚开始学习虚拟函数。
从我(在书中和网上)读到的内容来看,虚拟函数是基类中的函数,可以在派生类中重写。
但在本书的早些时候,当我学习基本继承时,我能够在派生类中重写基函数,而不使用虚函数。
那么我在这里错过了什么?我知道虚拟函数还有很多,它似乎很重要,所以我想清楚它到底是什么。我只是在网上找不到一个直截了当的答案。
我正在学习C++,我刚刚开始学习虚拟函数。
从我(在书中和网上)读到的内容来看,虚拟函数是基类中的函数,可以在派生类中重写。
但在本书的早些时候,当我学习基本继承时,我能够在派生类中重写基函数,而不使用虚函数。
那么我在这里错过了什么?我知道虚拟函数还有很多,它似乎很重要,所以我想清楚它到底是什么。我只是在网上找不到一个直截了当的答案。
当前回答
对虚拟函数的解释存在的问题是,它们没有解释如何在实践中使用它,以及它如何有助于维护。我创建了一个虚拟函数教程,人们已经发现它非常有用。此外,它基于战场前提,这让它更令人兴奋:https://nrecursions.blogspot.com/2015/06/so-why-do-we-need-virtual-functions.html.
考虑这个战场应用:
#include "iostream"
//This class is created by Gun1's company
class Gun1 {public: void fire() {std::cout<<"gun1 firing now\n";}};
//This class is created by Gun2's company
class Gun2 {public: void shoot() {std::cout<<"gun2 shooting now\n";}};
//We create an abstract class to interface with WeaponController
class WeaponsInterface {
public:
virtual void shootTarget() = 0;
};
//A wrapper class to encapsulate Gun1's shooting function
class WeaponGun1 : public WeaponsInterface {
private:
Gun1* g;
public:
WeaponGun1(): g(new Gun1()) {}
~WeaponGun1() { delete g;}
virtual void shootTarget() { g->fire(); }
};
//A wrapper class to encapsulate Gun2's shooting function
class WeaponGun2 : public WeaponsInterface {
private:
Gun2* g;
public:
WeaponGun2(): g(new Gun2()) {}
~WeaponGun2() { delete g;}
virtual void shootTarget() { g->shoot(); }
};
class WeaponController {
private:
WeaponsInterface* w;
WeaponGun1* g1;
WeaponGun2* g2;
public:
WeaponController() {g1 = new WeaponGun1(); g2 = new WeaponGun2(); w = g1;}
~WeaponController() {delete g1; delete g2;}
void shootTarget() { w->shootTarget();}
void changeGunTo(int gunNumber) {//Virtual functions makes it easy to change guns dynamically
switch(gunNumber) {
case 1: w = g1; break;
case 2: w = g2; break;
}
}
};
class BattlefieldSoftware {
private:
WeaponController* wc;
public:
BattlefieldSoftware() : wc(new WeaponController()) {}
~BattlefieldSoftware() { delete wc; }
void shootTarget() { wc->shootTarget(); }
void changeGunTo(int gunNumber) {wc->changeGunTo(gunNumber); }
};
int main() {
BattlefieldSoftware* bf = new BattlefieldSoftware();
bf->shootTarget();
for(int i = 2; i > 0; i--) {
bf->changeGunTo(i);
bf->shootTarget();
}
delete bf;
}
我鼓励您首先阅读博客上的文章,了解包装器类创建的原因。
如图所示,有各种火炮/导弹可以连接到战场软件,并且可以向这些武器发出命令,以进行射击或重新校准等。这里的挑战是能够在不必更改蓝色战场软件的情况下更改/更换火炮/导弹,并且能够在运行时切换武器,而无需更改代码并重新编译。
上面的代码显示了问题是如何解决的,以及具有精心设计的包装类的虚拟函数如何封装函数并帮助在运行时分配派生类指针。WeaponGun1类的创建确保了你将Gun1的处理完全分离到类中。无论你对Gun1做了什么改变,你只需要在WeaponGun1中做出改变,并有信心其他职业不会受到影响。
由于WeaponsInterface类,您现在可以将任何派生类分配给基类指针WeaponsIterface,并且因为它的函数是虚拟的,所以当您调用WeaponsIInterface的shootTarget时,派生类shootTarget将被调用。
最好的部分是,您可以在运行时更改枪(w=g1和w=g2)。这是虚拟函数的主要优势,这也是我们需要虚拟函数的原因。
因此,在更换枪支时,不再需要在不同的地方注释代码。现在,这是一个简单而干净的过程,添加更多的枪类也更容易,因为我们只需要创建一个新的WeaponGun3或WeaponGun 4类,我们可以确信它不会破坏BattlefieldSoftware的代码或WeaponGun1/WeaponGun2的代码。
其他回答
虚拟函数用于支持运行时多态性。
也就是说,virtual关键字告诉编译器不要在编译时做出(函数绑定的)决定,而是推迟到运行时”。
您可以通过在函数的基类声明中的关键字virtual之前使其成为虚拟函数。例如类基础{虚虚函数();}当基类具有虚拟成员函数时,从基类继承的任何类都可以使用完全相同的原型重新定义该函数,即只能重新定义功能,而不能重新定义函数的接口。类派生:公共基{void函数();}基类指针可用于指向基类对象和派生类对象。当使用基类指针调用虚拟函数时,编译器在运行时决定要调用函数的哪个版本(即基类版本或重写的派生类版本)。这被称为运行时多态性。
关键字virtual告诉编译器它不应该执行早期绑定。相反,它应该自动安装执行后期绑定所需的所有机制。为了实现这一点,典型的编译器1为每个包含虚拟函数的类创建一个表(称为VTABLE)。编译器将该特定类的虚拟函数的地址放在VTABLE中。在每个具有虚拟函数的类中,它都会秘密地放置一个指针,称为vpointer(缩写为VPTR),该指针指向该对象的VTABLE。当您通过基类指针进行虚拟函数调用时,编译器会悄悄地插入代码以获取VPTR并在VTABLE中查找函数地址,从而调用正确的函数并导致延迟绑定。
此链接中的详细信息http://cplusplusinterviews.blogspot.sg/2015/04/virtual-mechanism.html
对虚拟函数的解释存在的问题是,它们没有解释如何在实践中使用它,以及它如何有助于维护。我创建了一个虚拟函数教程,人们已经发现它非常有用。此外,它基于战场前提,这让它更令人兴奋:https://nrecursions.blogspot.com/2015/06/so-why-do-we-need-virtual-functions.html.
考虑这个战场应用:
#include "iostream"
//This class is created by Gun1's company
class Gun1 {public: void fire() {std::cout<<"gun1 firing now\n";}};
//This class is created by Gun2's company
class Gun2 {public: void shoot() {std::cout<<"gun2 shooting now\n";}};
//We create an abstract class to interface with WeaponController
class WeaponsInterface {
public:
virtual void shootTarget() = 0;
};
//A wrapper class to encapsulate Gun1's shooting function
class WeaponGun1 : public WeaponsInterface {
private:
Gun1* g;
public:
WeaponGun1(): g(new Gun1()) {}
~WeaponGun1() { delete g;}
virtual void shootTarget() { g->fire(); }
};
//A wrapper class to encapsulate Gun2's shooting function
class WeaponGun2 : public WeaponsInterface {
private:
Gun2* g;
public:
WeaponGun2(): g(new Gun2()) {}
~WeaponGun2() { delete g;}
virtual void shootTarget() { g->shoot(); }
};
class WeaponController {
private:
WeaponsInterface* w;
WeaponGun1* g1;
WeaponGun2* g2;
public:
WeaponController() {g1 = new WeaponGun1(); g2 = new WeaponGun2(); w = g1;}
~WeaponController() {delete g1; delete g2;}
void shootTarget() { w->shootTarget();}
void changeGunTo(int gunNumber) {//Virtual functions makes it easy to change guns dynamically
switch(gunNumber) {
case 1: w = g1; break;
case 2: w = g2; break;
}
}
};
class BattlefieldSoftware {
private:
WeaponController* wc;
public:
BattlefieldSoftware() : wc(new WeaponController()) {}
~BattlefieldSoftware() { delete wc; }
void shootTarget() { wc->shootTarget(); }
void changeGunTo(int gunNumber) {wc->changeGunTo(gunNumber); }
};
int main() {
BattlefieldSoftware* bf = new BattlefieldSoftware();
bf->shootTarget();
for(int i = 2; i > 0; i--) {
bf->changeGunTo(i);
bf->shootTarget();
}
delete bf;
}
我鼓励您首先阅读博客上的文章,了解包装器类创建的原因。
如图所示,有各种火炮/导弹可以连接到战场软件,并且可以向这些武器发出命令,以进行射击或重新校准等。这里的挑战是能够在不必更改蓝色战场软件的情况下更改/更换火炮/导弹,并且能够在运行时切换武器,而无需更改代码并重新编译。
上面的代码显示了问题是如何解决的,以及具有精心设计的包装类的虚拟函数如何封装函数并帮助在运行时分配派生类指针。WeaponGun1类的创建确保了你将Gun1的处理完全分离到类中。无论你对Gun1做了什么改变,你只需要在WeaponGun1中做出改变,并有信心其他职业不会受到影响。
由于WeaponsInterface类,您现在可以将任何派生类分配给基类指针WeaponsIterface,并且因为它的函数是虚拟的,所以当您调用WeaponsIInterface的shootTarget时,派生类shootTarget将被调用。
最好的部分是,您可以在运行时更改枪(w=g1和w=g2)。这是虚拟函数的主要优势,这也是我们需要虚拟函数的原因。
因此,在更换枪支时,不再需要在不同的地方注释代码。现在,这是一个简单而干净的过程,添加更多的枪类也更容易,因为我们只需要创建一个新的WeaponGun3或WeaponGun 4类,我们可以确信它不会破坏BattlefieldSoftware的代码或WeaponGun1/WeaponGun2的代码。
当基类中有函数时,可以在派生类中重新定义或重写它。
重新定义方法:派生类中给出了基类方法的新实现。不便于动态绑定。
重写方法:在派生类中重新定义基类的虚拟方法。虚拟方法有助于动态绑定。
所以当你说:
但在书的早些时候,当我了解基本遗传时能够重写派生类中的基方法,而不使用“虚拟”。
因为基类中的方法不是虚拟的,所以您不是在重写它,而是在重新定义它
底线是,虚拟功能使生活更轻松。让我们使用M Perry的一些想法,并描述如果我们没有虚拟函数而只能使用成员函数指针会发生什么。在没有虚函数的正常估计中,我们有:
class base {
public:
void helloWorld() { std::cout << "Hello World!"; }
};
class derived: public base {
public:
void helloWorld() { std::cout << "Greetings World!"; }
};
int main () {
base hwOne;
derived hwTwo = new derived();
base->helloWorld(); //prints "Hello World!"
derived->helloWorld(); //prints "Hello World!"
好的,这就是我们所知道的。现在让我们尝试使用成员函数指针:
#include <iostream>
using namespace std;
class base {
public:
void helloWorld() { std::cout << "Hello World!"; }
};
class derived : public base {
public:
void displayHWDerived(void(derived::*hwbase)()) { (this->*hwbase)(); }
void(derived::*hwBase)();
void helloWorld() { std::cout << "Greetings World!"; }
};
int main()
{
base* b = new base(); //Create base object
b->helloWorld(); // Hello World!
void(derived::*hwBase)() = &derived::helloWorld; //create derived member
function pointer to base function
derived* d = new derived(); //Create derived object.
d->displayHWDerived(hwBase); //Greetings World!
char ch;
cin >> ch;
}
虽然我们可以用成员函数指针做一些事情,但它们不如虚拟函数灵活。在类中使用成员函数指针是很棘手的;至少在我的实践中,成员函数指针几乎总是必须在主函数中或从成员函数中调用,如上面的示例所示。
另一方面,虚拟函数虽然可能有一些函数指针开销,但确实大大简化了事情。
EDIT:还有一种方法与eddietree类似:c++虚拟函数与成员函数指针(性能比较)。