基类与派生类的对象调用

下列代码之后的结果为(

adcee

#include<iostream>
using namespace std;
struct Base{
	int i;
	virtual int f() {
		cout<<"a";
		return 1;
	}
	virtual const Base &f() const {
		cout<<"b";
		return *this;
	}
	int g() {
		cout<<"c";
		return 3;
	}
};
struct Derive:Base {
	int i;
	int f() {
		cout<<"d";
		return 4;
	}
	const Base &f() const{
		cout<<"e";
		return *this;
	}
	int f(int=0) {
		cout<<"f";
		return 6;
	}
	virtual int g() {
		cout<<"g";
		return 7;
	}
};

int main() {
	Derive d;
	const Derive  d_const;
	Base b,*p=&d;
	const Base *p_const = &d_const;
	b.f();
	p->f();
	p->g();
	p_const->f();
	d_const.f();
}

  

1.b.f(); 基类对象直接调用基类的f()函数,输出a
2.p->f(); 派生类对象赋给基类的指针,由于f()在基类中是虚函数,根据基类指针指向的对象进行调用,因此调用派生类的int f()输出d
3.p->g();基类中g()不是虚函数,调用基类的g()
4.p_const->f();常对象,又由于基类中声明为虚,同理用派生类中的函数
5.同理
 
 
只有在通过基类指针(或引用)间接指向派生类子类型时多态性才会起作用。派生类的指针只调用自己的函数!基类指针的函数调用如果有virtual则根据多态性调用派生类的函数,如果没有virtual则是正常调用基类的函数。
拥抱明天! 不给自己做枷锁去限制自己。 别让时代的悲哀,成为你人生的悲哀。
原文地址:https://www.cnblogs.com/dd2hm/p/7290366.html