关于虚拟函数的有关问题
关于虚拟函数的问题.
有2个程序,如下:
\\1:
#include <iostream.h>
class A
{
public:
A(){cout < < "1 " < <endl;}
void virtual move() const {cout < < "this A one step " < <endl;}
void move(int i) const {cout < < "this A " < <i < < " step " < <endl;}
private:
int i;
};
class B : public A
{
public:
void move() const {cout < < "this B one step " < <endl;}
};
void main()
{
A biganimal;
B fido;
A *p=new A;
p-> move();
}
/*结果为:
1
1
1
this A one step
*/
\\2:
#include <iostream.h>
class A
{
public:
A(){cout < < "1 " < <endl;}
void virtual move() const {cout < < "this A one step " < <endl;}
void move(int i) const {cout < < "this A " < <i < < " step " < <endl;}
private:
int i;
};
class B : public A
{
public:
void move() const {cout < < "this B one step " < <endl;}
};
void main()
{
A biganimal;
B fido;
A *p=new B;
p-> move();
}
/*结果为:
1
1
1
this B one step
*/
我是这样认为的,在2中当p指向新对象返回A指针时候,是不可以调用A中的虚拟函数move的.
而在1中,A *p=new A后,却可以调用虚拟函数,这是为什么呢?是不是向2这样的情况有虚函数出现就不问它了?直接看下面的?
------解决方案--------------------
呃,楼主,你还是找本C++ Primer认真看看虚函数的章节吧。3言2语讲不清楚的。
------解决方案--------------------
c++中的动态绑定机制
调用的是实际指向对象的虚函数
------解决方案--------------------
虚拟函数根据的指针所指的对象执行
A *p=new A;p指向一个A对象,所以执行A的虚拟函数
A *p=new B;p指向一个B对象,所以执行B的虚拟函数^_^
有2个程序,如下:
\\1:
#include <iostream.h>
class A
{
public:
A(){cout < < "1 " < <endl;}
void virtual move() const {cout < < "this A one step " < <endl;}
void move(int i) const {cout < < "this A " < <i < < " step " < <endl;}
private:
int i;
};
class B : public A
{
public:
void move() const {cout < < "this B one step " < <endl;}
};
void main()
{
A biganimal;
B fido;
A *p=new A;
p-> move();
}
/*结果为:
1
1
1
this A one step
*/
\\2:
#include <iostream.h>
class A
{
public:
A(){cout < < "1 " < <endl;}
void virtual move() const {cout < < "this A one step " < <endl;}
void move(int i) const {cout < < "this A " < <i < < " step " < <endl;}
private:
int i;
};
class B : public A
{
public:
void move() const {cout < < "this B one step " < <endl;}
};
void main()
{
A biganimal;
B fido;
A *p=new B;
p-> move();
}
/*结果为:
1
1
1
this B one step
*/
我是这样认为的,在2中当p指向新对象返回A指针时候,是不可以调用A中的虚拟函数move的.
而在1中,A *p=new A后,却可以调用虚拟函数,这是为什么呢?是不是向2这样的情况有虚函数出现就不问它了?直接看下面的?
------解决方案--------------------
呃,楼主,你还是找本C++ Primer认真看看虚函数的章节吧。3言2语讲不清楚的。
------解决方案--------------------
c++中的动态绑定机制
调用的是实际指向对象的虚函数
------解决方案--------------------
虚拟函数根据的指针所指的对象执行
A *p=new A;p指向一个A对象,所以执行A的虚拟函数
A *p=new B;p指向一个B对象,所以执行B的虚拟函数^_^