虚函数的使用
先看错误代码(无virtual版本)#include <iostream>using namespace std;class base1{public:void show()const{cout<<"showing base1"<<endl;}};class base2: public base1{public:void show()const{cout<
·
先看错误代码(无virtual版本)
#include <iostream>
using namespace std;
class base1{
public:
void show()const{
cout<<"showing base1"<<endl;
}
};
class base2: public base1{
public:
void show()const{
cout<<"showing base2"<<endl;
}
};
class derived: public base2{
public:
void show()const{
cout<<"showing derived"<<endl;
}
};
void show(base1*i){
i->show();
}
int main(){
base1 b1;
base2 b2;
derived d;
show(&b1);
show(&b2);
show(&d);
return 0;
}
这是因为没有virtual
结果是
加了virtual关键字之后
#include <iostream>
using namespace std;
class base1{
public:
virtual void show()const{
cout<<"showing base1"<<endl;
}
};
class base2: public base1{
public:
void show()const{
cout<<"showing base2"<<endl;
}
};
class derived: public base2{
public:
void show()const{
cout<<"showing derived"<<endl;
}
};
void show(base1*i){
i->show();
}
int main(){
base1 b1;
base2 b2;
derived d;
show(&b1);
show(&b2);
show(&d);
return 0;
}
结果是
原因:show函数需要在编译时候就确定,但是因为我们调用的时候不能确定,所以要在base1那里加个virtual(动态绑定)
ps:写void show(base1*i)的时候竟然写成了base1&i,深感code力下降qaq
更多推荐
已为社区贡献3条内容
所有评论(0)