C++基础之关键字——virtual详解

27 篇文章 2 订阅

修饰父类中的普通函数
被修饰的函数称为虚函数, 是C++中多态的一种实现(多说一句,多态分编译时多态-通过重载实现和运行时多态-通过虚函数实现)。 也就是说用父类的指针或者引用指向其派生类的对象,当使用指针或引用调用函数的时候会根据具体的对象类型调用对应对象的函数(需要两个条件:父类的函数用virtual修饰和子类要重写父类的函数)。下面用一个例子来说明:

#include <iostream>

class father {
public:
	void func1() {std::cout << "this is father func1" << std::endl;}
	virtual void func2() {std::cout << "this is father func2" << std::endl;
}

class son:public father {
public:
	void func1() {std::cout << "this is son func1" << std::endl;}
	void func2() {std::cout << "this is son func2" << std::endl;
}

int main() {
	father *f1 = new son();
	f1.func1();
	f1.func2();
	return 0;
}

output:

this is father func1
this is son func2

通过上面的例子可以看出,使用virtual修饰的函数会根据实际对象的类型来调用,没有使用virtual修饰的根据指针的类型来调用。虚函数最关键的特点是“动态联编”,它可以在运行时判断指针指向的对象,并自动调用相应的函数。
在这里插入图片描述

#include<iostream>
#include<vector>
using namespace std;


class solution
{
	public:
		float x;
		float y;
	public:
   	void move(float xx,float yy){
		x += xx;
		y += yy;
	}
	solution(){
		x = 0;
		y = 0;
	}
   virtual	void print(){
		cout<<"solution!"<<endl;
	}
};

class answer:public solution
{
	
	public:
		float y;
	public:
		answer(float a):y(a){
			
		 cout<<y<<endl;
		}
		
	 void print(){
		cout<<"answer!"<<endl;
	}
	
	
};

int main(){
	/*answer sol;
	sol.move(1,2);
	//solution sol;
	sol.print();
	sol.move(1,2);
	sol.print();*/
	answer* answ = new answer(100);
    //sol->move(1,2); 
    answ->print();
    //sol->printf(111);
    solution *sol = new solution();
    sol->print();
    cout<<"test!~"<<endl;
    solution *test = answ;
    test->print(); 
}   

纯虚函数:
在这里插入图片描述

Reference
1.最好的C++学习教程(上篇)——The Cherno CppSeries

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jack Ju

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值