C++ 虛擬函式

心鑫發表於2014-03-22

/*
 * Brass.h
 *
 *  Created on: 2014-3-22
 *      Author: Administrator
 */

#ifndef BRASS_H_
#define BRASS_H_

class Brass {
public:
	Brass();
	virtual void showVirtual();
	void show();
	virtual ~Brass();
};
class BrassPlus: public Brass {
public:
	virtual void showVirtual();
	virtual ~BrassPlus();
	void showPlus();
	void show();
};
#endif /* BRASS_H_ */




/*
 * Brass.cpp
 *
 *  Created on: 2014-3-22
 *      Author: Administrator
 */

#include "Brass.h"
#include <iostream>
using namespace std;

Brass::Brass() {
	// TODO Auto-generated constructor stub

}

Brass::~Brass() {
	cout << "~Brass" << endl;
}
void Brass::showVirtual() {
	cout << "Brass showVirtual" << endl;
}
void BrassPlus::showVirtual() {
	cout << "BrassPlus showVirtual" << endl;
}
void Brass::show() {
	cout << "Brass show" << endl;
}
void BrassPlus::show() {
	cout << "BrassPlus show" << endl;
}
void BrassPlus::showPlus() {
	cout << "BrassPlus showPlus" << endl;
}
BrassPlus::~BrassPlus() {
	cout << "~BrassPlus" << endl;
}



#include "Brass.h"
int main() {
	BrassPlus bp1;
	Brass *b2 = &bp1;
	Brass b3 = bp1;
	Brass& b4 = bp1;
	bp1.showVirtual();
	b2->showVirtual();
	b3.showVirtual();
	b4.showVirtual();
//	BrassPlus showVirtual
//	BrassPlus showVirtual
//	Brass showVirtual
//	BrassPlus showVirtual

	bp1.show();
	b2->show();
	b3.show();
	b4.show();
//	BrassPlus show
//	Brass show
//	Brass show
//	Brass show

	return 0;  //~Brass ~BrassPlus ~Brass
}


總結:

子類輸值給父類 都是父類的方法

使用虛擬函式,指標引用將呼叫子類的方法,不使用虛擬函式呼叫的父尖的方法

解構函式的呼叫,b3先清除 解構函式呼叫, b1清除呼叫子類的解構函式,因採用虛擬函式父類的解構函式自動呼叫(不要再子解構函式中顯性呼叫,


java中子類輸值給父類,只是傳引用地址,所以呼叫的還是子類的方法




Brass b1;
	BrassPlus& bp1 = (BrassPlus &) b1;
	bp1.show();
	bp1.showPlus();

BrassPlus show
BrassPlus showPlus
~Brass


總結2:

父類強制轉換成子類,要用引用轉換

不明白為什麼呼叫的是子類的方法















相關文章