根据我的书,如果我想创建一个不在同一个类但在同一个类层次结构中的对象数组,我需要使用指针:
class text
{
public:
void write(string text);
void show();
private:
string texte;
};
void text::write(string text)
{
texte = text;
}
void text::show()
{
cout << texte;
}
class text_with_stars : public text
{
public:
void show();
};
void text_with_stars::show()
{
cout << "*";
text::show();
cout << "*";
}
int main()
{
text* array[2];
array[0] = new text;
array[0]->write("Hello");
text_with_stars* pointer = new text_with_stars;
pointer->write("Hi");
array[1] = pointer;
for (int i=0;i<2;i++)
{
array[i]->show();
}
return 0;
}
但是当我这样做时,输出是“HelloHi”,这意味着第二个对象使用的是来自text而不是text_with_stars的show版本,但我完全按照本书描述的方式进行了操作。有什么问题??
以下是书中所写的内容:
Question* quiz[2]; quiz[0] = new Question; quiz[0]->set_text("Who was the inventor of C++?"); quiz[0]->set_answer("Bjarne Stroustrup"); ChoiceQuestion* cq_pointer = new ChoiceQuestion; cq_pointer->set_text("In which country was the inventor of C++ born?") cq_pointer->add_choice("Australia",false); ... quiz[1] = cq_pointer;
我正在阅读的那一章的章节是关于虚函数的,它解释了系统将始终使用Question的成员函数而不是ChoiceQuestion,看起来我应该在互联网上提问之前阅读更多内容!
答案 0 :(得分:3)
void show()
如果要使用基类指针派生类中的方法,需要在基类中是虚拟的
答案 1 :(得分:1)
发生这种情况的原因是因为您调用的函数是非虚拟。
假设我们从父母那里继承了class Parent
和class Child
:
class Parent {
public:
void f() {
cout << "Parent::f()" << endl;
}
};
class Child : public Parent {
public:
void f() {
cout << "Child::f()" << endl;
}
};
现在,让我们指向Parent
并在其中存储Child
(多态):
Parent *ptr = new Child;
ptr->f();
此时,编译器看到ptr
的类型为Parent*
,并确定要调用的函数是Parent :: f()。
为了在处理多态时调用Child::f()
?必须定义Parent::f()
virtual
。然后编译器生成代码以在运行时检查存储在内存中的值以调用适当的(子)函数。
简而言之:仅当函数是虚函数并在指针或引用上调用时,才会进行内存查找以确定内存中该点的实际类型。否则就不是。