虚函数 继承 出错的debug

文章讨论了在C++中使用面向对象编程时遇到的虚函数问题。具体表现为在基类中声明了虚函数但未定义,导致编译错误。解决方案是将基类的虚函数设为纯虚函数,以强制子类重写这些函数。同时,文章提供了修改后的代码示例,包括将动态分配的对象改为栈上创建,以及调整main函数中对象的使用方式。
摘要由CSDN通过智能技术生成

项目场景:

在学习面向对象的时候,需要用到一些虚函数。
这里的虚函数,大概就是因为写成函数声明,没写成纯虚函数而导致的报错。


问题描述

这里的虚函数有问题,现在不知道怎么回事,以后来改。

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值