Cherno视频:https://www.youtube.com/watch?v=oIV2KchSyGQ&list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb&index=28
子类包含了父类所有的public,protected属性:
#include<iostream>
class Entity {
public:
float X, Y;
void Move(int ax, int ay) {
X += ax;
Y += ay;
}
};
class Player :Entity
{
public:
char * name;
char * GetName()const {
return name;
}
};
int main() {
std::cout << "sizeof(Entity): "<<sizeof(Entity) << std::endl;
std::cout << "sizeof(Player): "<<sizeof(Player) << std::endl;
std::cin.get();
}
virtual function
dynamic dispatch --->compile is typically implemented by our V table
a V table is a table which contains a mapping for all the virtual functions inside out base class
so that we can map them to the correct overwritten function at runtime
class Entity {
public:
virtual std::string GetName() const {//virtual -->tell compiler to generate a V table for this function
return "Entity"; //so that if it is overwritten youcan point to the correct function with this table
}
};
class Player : public Entity
{
public:
Player(const std::string& name):
m_name(name){}
std::string m_name;
std::string GetName() const override{
return m_name;
}
};
void PrintName(Entity* entity) {
std::cout << entity->GetName() << std::endl;
}
int main() {
Entity* e = new Entity();
PrintName(e);
Player* p = new Player("Cherno");
PrintName(p);
std::cin.get();
}
注意:
virtual function has two runtime costs:
1.have additional memery to store V table,
includes a member pointer in the actual base class that points to the V table (基类中含有一个指向V-table的指针)
2. when we call a virtual function we have to go through V table to determine which function to actually map to(每次调用虚函时,都需要在V-table中查找)