项目场景:
在学习面向对象的时候,需要用到一些虚函数。
这里的虚函数,大概就是因为写成函数声明,没写成纯虚函数而导致的报错。
问题描述
这里的虚函数有问题,现在不知道怎么回事,以后来改。
#include <bits/stdc++.h>
using namespace std;
class Library{
public:
void step1(){
cout << "1\n";
}
virtual bool step2();
void step3(){
cout << "3\n";
}
virtual void step4();
void step5(){
cout << "5\n";
}
virtual ~Library(){
cout << "des for lib\n";
}
};
class App1 : public Library{
public:
bool step2(){
return 1;
}
void step4(){
cout<<"4\n";
}
void run(){
step1();
if(step2()){
step3();
}
for(int i = 0; i < 4; i ++){
step4();
}
step5();
}
~App1(){
cout<<"des for app1\n";
}
};
class App2 : public Library{
public:
bool step2(){
return 1;
}
void step4(){
cout<<"4_2\n";
}
void run(){
step1();
if(step2()){
step3();
}
for(int i = 0; i < 4; i ++){
step4();
}
step5();
}
~App2(){
cout<<"des for app2\n";
}
};
int main(){
App1* app1 = new App1();
App2* app2 = new App2();
app1->run();
app2->run();
delete app1;
delete app2;
return 0;
}
原因分析:
提示:这里填写问题的分析:
在父类中,虚函数只写成定义了,也没有写成纯虚函数。
解决方案:
提示:这里填写该问题的具体解决方案:
1.这里是直接把最后main代码改为下面的
int main(){
App1 app1;
App2 app2;
app1.run();
app2.run();
return 0;
}
2.该方案更为正确。
将父类虚函数设置为纯虚函数
class Library{
public:
void step1(){
cout << "1\n";
}
virtual bool step2() = 0;
void step3(){
cout << "3\n";
}
virtual void step4() = 0;
void step5(){
cout << "5\n";
}
void run(){
step1();
if(step2()){
step3();
}
for(int i = 0; i < 4; i ++){
step4();
}
step5();
}
// virtual ~Library();
};
main函数
int main(){
Library* app1 = new App1();
Library* app2 = new App2();
app1->run();
app2->run();
return 0;
}