虚函数的整个思想是什么
What is the whole idea of virtual function?
在代码中,我能够成功地将派生类指针指向基类对象,并且我还能够设置和获取基类私有成员的值。如果这没有给任何问题,那么什么是虚函数的需要,以及围绕运行时多态性/延迟绑定/虚表之类的混乱!!
#include <iostream>
using namespace std;
class Base
{
int a;
public:
Base(int x=0):a(x){}
void setValueForMember(int p)
{
a=p;
}
void showValueOfMember(){cout<<endl<<a<<endl;}
};
class Derived:public Base
{
int b;
public:
Derived(){}
Derived(int y):b(y){}
void setValueForMember(int q)
{
b=q;
}
void showValueOfMember(){cout<<endl<<b<<endl;}
};
int main()
{
Derived D;
D.setValueForMember(10);
Derived *Dptr = new Derived();
Dptr = &D;
Dptr->showValueOfMember();
Base B;
Dptr = (Derived*)&B;
Dptr->setValueForMember(20);
Dptr->showValueOfMember();
return 0;
}
虚函数用于希望使用基类类型的指针访问派生类的成员的情况。
- 何时使用
Bptr =研发;
将不能访问派生类的成员,除了从基类继承的成员。如果希望使用与Bptr相同的指针访问派生类的成员,则必须使用虚函数
- 在编译时决定执行哪个函数,这就是为什么它被称为
运行时多态性或动态绑定
。
相关文章:
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 是什么原因导致它无法编译?它是声明签名还是在函数本身的实现中
- 是什么让放置新调用对象的构造函数?
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 在函数中拥有函数原型的目的是什么?
- 使用基类指针调用基类的值构造函数的语法是什么?
- C++:使用方法调用析构函数的顺序是什么?
- 将此布尔值传递给此函数的最有效方法是什么?
- * 和 ** 在 C++ 函数声明中是什么意思?
- C++:Lambda 函数指针转换的用例是什么?
- C++关于指针和使用函数将它们启动到堆的行为究竟是什么?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 在将函数声明为友元时,尖括号的含义是什么?
- 在模板类之外定义友元函数的正确方法是什么?
- 在使用包含冒号的类似函数的宏时,是什么导致了这种编译器差异?
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 这里的字符串函数是什么意思
- 传递 lambda 函数的权衡是什么?
- 在C 中,对2D数组的增量是什么?函数断言(0)做什么?