使用基对象和派生对象的虚函数
Virtual functions using base and derived objects
我已经阅读了vtable,并且已经理解了指向基类和派生类对象的基类指针的概念。有人可以解释一下当基类和派生类都是对象并且派生类对象分配给基类对象时如何创建 vtable 的情况。以下示例中的情况 3
#include <iostream>
#include <exception>
using namespace std;
class Base
{
public:
virtual void function1() { cout<<"Base - func1"<<endl; }
virtual void function2() { cout<<"Base - func2"<<endl; }
};
class Derived1: public Base
{
public:
virtual void function1() { cout<<"Derived1 - func1"<<endl; }
};
class Derived2: public Base
{
public:
virtual void function2() { cout<<"Derived2 - func2"<<endl; }
};
int main ()
{
// Case 1
Base* B1 = new Derived1();
B1->function1();
B1->function2();
// Case 2
cout<<endl;
Base* B2 = new Derived2();
B2->function1();
B2->function2();
// Case 3
cout<<endl;
Base B3;
Derived1 D1;
B3=D1;
B3.function1();
B3.function2();
}
输出:
Derived1 - func1
Base - func2
Base - func1
Derived2 - func2
Base - func1
Base - func2
B3=Derived;
是对象切片的一个例子...仅将基类数据成员分配给基类,并且 vtable 指针继续指向基类函数。
您应该避免切片 - 它可能很危险(有关解释,请参阅此答案(。 现在您知道了这个术语,您将很容易找到有关对象切片的大量阅读......
Base B3;
D1 Derived;
B3=Derived; //There is called default assignment operator
它的定义是这样的:
Base& operator=(const Base &objectToCopy) {...}
运算符采用类型 Base
的参数,因此类型 D1
的对象被视为类型 Base
的对象。这意味着赋值运算符只能看到类Base
中的Derived
字段。但是,指向vtable
的指针(技术上是一个隐藏字段(仍然不会被复制,因为它总是在构造函数中创建,并且它与实际对象类型永久关联。
相关文章:
- 如何创建对象函数指针C++映射?
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- 如何将对象函数的实例传递给另一个函数
- 调用模板函数的问题"No matching function for call"参数:迭代器、对象函数
- makefile对我的名称空间对象/函数/构造函数的不确定引用
- 将对象函数转换为函数指针
- 非对象函数/类函数C++
- 线程对象函数 C++
- C 将成员对象函数分配给类成员功能
- 使用基本指针调用派生对象函数
- 可以(通过编译器)使用多少个线程来初始化全局对象(函数main之前)
- C++类对象函数
- 对对象::函数的未定义引用
- 无法弄清楚将多个对象函数作为单独的线程调用的语法
- 在提升作用域出口中调用对象函数
- 使用基指针来使用派生对象函数
- 在for_each lambda 中调用对象函数
- C++:: 模板函数 - 从对象函数获取对象的地址
- Qt5 未解析的外部静态元对象函数
- 通过变量使用对象和对象函数