所以我试图使用dynamic_cast
调用派生类对象方法 template<class T>
void stack<T>::objOps()
{
T* a = this->arr[top];
char s;
Gorilla* TempGorill = dynamic_cast<Gorilla*>(a);
cout << "Select Object Functions: " << endl << endl
<< "<R>oar" << endl;
if (TempGorill) { cout << "Chest<B>eating" << endl; }
else { cout << "<M>akeFire" << endl << endl; }
cout << "Your Choice-> "; cin>>(s);
switch(s)
{
case 'R': case 'r': a->roaR();
if( TempGorill)
{ case 'B': case 'b': a->chestBeating(); }
else { case 'M': case 'm': a->makeFire(); }
}
}
roaR是好的,因为它在猴子中是纯粹的虚拟,但是胸部在Goriila中是排他性的,在黑猩猩中是makeFire,它们都是猴子的派生类。
奇怪的是,根据我选择大猩猩或黑猩猩,它打印正确的方法,但无法访问他们的方法
我得到的错误:
>c:\users\eizzy\documents\visual studio 2010\projects\copiedproject\copiedproject\newstack.h(135): error C2039: 'chestBeating' : is not a member of 'monkey'
1> c:\users\eizzy\documents\visual studio 2010\projects\copiedproject\copiedproject\monkey.h(8) : see declaration of 'monkey'
1> c:\users\eizzy\documents\visual studio 2010\projects\copiedproject\copiedproject\newstack.h(122) : while compiling class template member function 'void stack<T>::objOps(void)'
c:\users\eizzy\documents\visual studio 2010\projects\copiedproject\copiedproject\newstack.h(136): error C2039: 'makeFire' : is not a member of 'monkey'
1> c:\users\eizzy\documents\visual studio 2010\projects\copiedproject\copiedproject\monkey.h(8) : see declaration of 'monkey'
感谢您的帮助。
答案 0 :(得分:0)
在你的开关范围内,你不应该做'TempGorill-&gt; chestBeating()'吗?