文章阅读
C++中使用virtual虚函数
2025/12/1664 次阅读2 分钟
#include <iostream>
class Entity {
public:
virtual std::string getName() { return "hello"; }
};
class MyPerson : public Entity {
public:
std::string getName() override {
return "ldd";
}
};
int main() {
Entity entity;
MyPerson person;
const auto basic_string = entity.getName();
const auto name = person.getName();
Entity *person2 = &person;
std::cout << basic_string << std::endl;
std::cout << name << std::endl;
std::cout << person2->getName() << std::endl;
return 0;
}
输出

还有一种纯虚函数,可以理解为Java中的接口
它的表现形式在末尾添加=0;
//Entity不能直接使用,因为有纯虚函数
class Entity {
public:
virtual std::string getName() { return "hello"; }
virtual void printName() = 0;//它的派生类必须实现这个方法
};
不能直接使用,会报错
