引用用户Steve314在 Why do we need virtual functions in C++? 上的回答:
With "virtual" you get "late binding". Which implementation of the method is used gets decided at run time based on the type of the pointed-to object - what it was originally constructed as. This is not necessarily what you'd think based on the type of the pointer that points to that object.
我偶然发现了以下示例:
class Shape
{
std::string name;
friend std::ostream& operator<<(std::ostream&, const Shape&);
public:
Shape(const std::string&);
virtual double circumference() = 0;
virtual ~Shape() {}
protected:
virtual void print(std::ostream&) const;
};
在继承自 Shape 的类中(例如 Circle、Square...),虚函数被重写。 circumference() 方法就是这种情况。
我的问题如下:如果circumference()是一个无法被调用的抽象方法(因为Shape是一个抽象类),为什么我们要把它变成一个虚函数,而不是简单地让它保持抽象并像往常一样重写它在派生类中?
如果我理解正确的话,我们会创建一个虚拟方法来确保“后期绑定(bind)”。例如。如果我们有以下代码块:
Shape *circle = new Circle();
double circ = circle->circumference();
通过将circumference()设为虚拟,我们确保将调用我们所指向对象的类类型的方法,而不是“声明”类型的方法(这里我们要调用Circle类的方法) )。
那么,如果以任何方式调用 Shape 类的circumference() 都会导致编译时错误(使其不可能发生),为什么我们将其设为虚拟而不只是抽象?
最佳答案
附加了 = 0
的虚拟
方法是抽象方法的定义。没有virtual
关键字就没有抽象方法这样的东西。
double circumference() = 0;
这只是一个语法错误。非虚拟
方法必须有定义。它不能是抽象的且具有 = 0
。
这样想:
- 该方法是否需要后期绑定(bind),以便调用的确切实现在运行时会有所不同?如果是这样,则将其标记为
虚拟
。 - 如果它是
虚拟
,基类是否想要提供默认实现?如果没有,则添加= 0
。
如果没有步骤 1,则无法执行步骤 2。
关于c++ - 虚拟抽象方法的语义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47728894/