所以我有以下代码:
#include <iostream>
using namespace std;
class Parent
{
int x;
public:
Parent(){x=10;}
void f(){cout<<x;}
};
class Child: public Parent
{
int x;
public:
Child(){x=20;}
void f(){cout<<x;}
};
int main()
{
Parent *pp;
Child c;
pp=&c;
pp->f();
return 0;
}
如您所见,我有两个类,从父类公开继承的父类和子类,所以我想看看如何使用指向父类的指针。
我认为可以像我在main中一样使用指向父类的指针并将其用于子对象上,但是,每当我运行此代码时,它都会打印出10,这是我拥有的值对于父类变量x,考虑到我使pp指向子对象,它不应该调用子类中定义的函数f(),因此应该打印20的值。任何帮助表示赞赏!
答案 0 :(得分:1)
方法f
必须是虚拟的。首先阅读this reference可能会有帮助。
#include <iostream>
using namespace std;
class Parent
{
int x;
public:
Parent(){x=10;}
virtual void f(){cout<<x;}
// ^^^^^^^ see this
};
class Child: public Parent
{
int x;
public:
Child(){x=20;}
virtual void f(){cout<<x;}
// ^^^^^^^ and this
// or since C++11 with override:
// void f() override {cout<<x;}
};
int main()
{
Parent *pp;
Child c;
pp=&c;
pp->f();
return 0;
}
答案 1 :(得分:1)
代码中至少有两个问题。
首先,必须至少在f()
类中将函数virtual
声明为Parent
(对于C ++ 11和更高版本,最好将关键字{{1 }}中的override
类)。函数Child
是一种机制,可以通过virtual
指针调用Child
实现。
第二,在Parent
和x
类中都声明变量Parent
。这意味着Child
对象具有两个名为Child
的变量,并且默认情况下x
函数中的x
将引用{{1}中声明的Child
}类(x
类中的副本必须是Child
或Parent
才能从public
访问,并且由于名称重叠,因此必须通过protected
类型指针,或通过像Child
中那样显式指定类。