求C++大神,下面的代码错在哪里了?怎么编译不通过?
#include<iostream>usingnamespacestd;classPerson{public:virtualvoidShow(){cout<<"我是per...
#include<iostream>
using namespace std;
class Person
{
public:
virtual void Show()
{
cout<<"我是person"<<endl;
}
};
class Student:public Person{};
class Teacher:public Person{};
class CppTeacher:public Teacher{};
class Computer
{
public:
void start(){}
};
class company
{
public:
void Test(Person*p)
{
Student*p1=dynamic_cast<Student*>(p);
if(p1)
{
cout<<"是学生"<<endl;
}
Teacher*p2=dynamic_cast<Teahcer*>(p);
if(p2)
{
cout<<"shi老师"<<endl;
}
CppTeacher*p3=dynamic_cast<CppTeacher*>(p);
if(p3)
{
cout<<"Cpp Teacher"<<endl;
}
if(p2&&p3)
{
cout<<"既是C++又是teacher"<<endl;
}
}
};
class Notebook:public Computer{};
int main()
{
Computer*c=new Notebook();
//dynamic_cast<Notebook*>(p)强制转换为Notebook型指针
//只要是基类中有虚函数就可以
Person*ps=new Student;
Person*pt=new Teacher();
Person*pc=new CppTeacher();
company pl;
pl.Test(pc);
pl.Test(ps);
pl.Test(pt);
return 0;
} 展开
using namespace std;
class Person
{
public:
virtual void Show()
{
cout<<"我是person"<<endl;
}
};
class Student:public Person{};
class Teacher:public Person{};
class CppTeacher:public Teacher{};
class Computer
{
public:
void start(){}
};
class company
{
public:
void Test(Person*p)
{
Student*p1=dynamic_cast<Student*>(p);
if(p1)
{
cout<<"是学生"<<endl;
}
Teacher*p2=dynamic_cast<Teahcer*>(p);
if(p2)
{
cout<<"shi老师"<<endl;
}
CppTeacher*p3=dynamic_cast<CppTeacher*>(p);
if(p3)
{
cout<<"Cpp Teacher"<<endl;
}
if(p2&&p3)
{
cout<<"既是C++又是teacher"<<endl;
}
}
};
class Notebook:public Computer{};
int main()
{
Computer*c=new Notebook();
//dynamic_cast<Notebook*>(p)强制转换为Notebook型指针
//只要是基类中有虚函数就可以
Person*ps=new Student;
Person*pt=new Teacher();
Person*pc=new CppTeacher();
company pl;
pl.Test(pc);
pl.Test(ps);
pl.Test(pt);
return 0;
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询