覆盖vs虚拟 [英] Overriding vs Virtual
问题描述
在函数前使用保留字virtual的目的是什么?如果我想要一个子类来覆盖父函数,我只是声明相同的函数,如 void draw(){}
。
class Parent {
public:
void say(){
std :: cout << 1;
}
};
class Child:public Parent {
public:
void say()
{
std :: cout< 2;
}
};
int main()
{
child * a = new Child();
a-> say();
return 0;
}
输出为2.
$ b b
所以再次,为什么在 say()
?的标题中需要保留字 virtual
/ p>
感谢一堆。
多态性工作我认为。主要的想法是,你想要抽象每个对象的具体类型。换句话说:你想要在不知道它是一个孩子的情况下调用Child实例!
下面是一个例子:
假设你有Child 和类Child2和Child3你想通过他们的基类(Parent)引用它们。
父母[3]
parents [0] = new Child();
parents [1] = new Child2();
parents [2] = new Child3();
for(int i = 0; i <3; ++ i)
parents [i] - > say();
你可以想象,这是非常强大的。它允许你根据需要扩展Parent多次,并且使用Parent指针的函数仍然可以工作。为了这个工作像其他人提到你需要声明方法为虚拟。
What is the purpose of using the reserved word virtual in front of functions? If I want a child class to override a parent function, I just declare the same function such as void draw(){}
.
class Parent {
public:
void say() {
std::cout << "1";
}
};
class Child : public Parent {
public:
void say()
{
std::cout << "2";
}
};
int main()
{
Child* a = new Child();
a->say();
return 0;
}
The output is 2.
So again, why would the reserved word virtual
be necessary in the header of say()
?
Thanks a bunch.
This is the classic question of how polymorphism works I think. The main idea is that you want to abstract the specific type for each object. In other words: You want to be able to call the Child instances without knowing it's a child!
Here is an example: Assuming you have class "Child" and class "Child2" and "Child3" you want to be able to refer to them through their base class (Parent).
Parent[3] parents;
parents[0] = new Child();
parents[1] = new Child2();
parents[2] = new Child3();
for (int i=0;i<3;++i)
parents[i]->say();
As you can imagine, this is very powerful. It let's you extend the Parent as many times as you want and functions that take a Parent pointer will still work. For this to work as others mention you need to declare the method as virtual.
这篇关于覆盖vs虚拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!