现在的位置: 首页 > 综合 > 正文

C++沉思录代理类

2014年01月04日 ⁄ 综合 ⁄ 共 1758字 ⁄ 字号 评论关闭

 

前几天看的时候没看明白书里头说的对copy的调用都是虚调用的意思。我还理解成虚调用就相当于啥都没干,然后就百思不得其解了。难道是因为翻译的问题,可惜木有英文版,本来对照着看看

今天跑了下代码,其实就是说copy函数是个虚函数嘛,具体行为要看它实际的绑定对象是什么,就调用对应对象的copy函数。

 

 

surrogate(代理类)

Vehicle parking_lot[1000];

Automobile x=/**/

parking_lot[num_vehicles++]=x;

假设Vehicle是Authomobile的基类

会把x slicing(切片),把x转成Vehicle对象,丢失Vehicle类中没有的信息。 

解决方案是存储指针,而不是对象本身。

Vehicle * parking_lot[1000];

Automobile x=/**/

parking_lot[num_vehicles++]=&x;

但也带来了问题,一旦x没有了,parking_lot就不知道指向什么东西了

 

变通一下使parking_lot指向原来的副本的指针

Automobile x=/**/

parking_lot[num_vehicles++]=new Automobile(x) ;

 

 

 

#include<iostream>
using namespace std;

class Vehicle  
{  
public:  
	virtual double weight() const = 0;  
	virtual void start() = 0;  
	virtual Vehicle* copy() const = 0;  
};  
class RoadVehicle:public Vehicle{
public:
	double weight()const{return 1.0;}
	void start(){cout<<"RoadVehicle start"<<endl; }
	Vehicle *copy()const{return new RoadVehicle(*this);}
};
class AutoVehicle : public Vehicle  
{  
public:  
	double weight() const { return 2.0; }  
	void start() { cout<<"Automobile start"<<endl; }  
	Vehicle* copy() const { return new AutoVehicle(*this); }  
};  
class Aircraft : public Vehicle  
{  
public:  
	double weight() const { return 3.0; }  
	void start() { cout<<"Aircraft start"<<endl; }  
	Vehicle* copy() const { return new Aircraft(*this); }  
};  
class Helicopter : public Vehicle  
{  
public:  
	double weight() const { return 4.0; }  
	void start() { cout<<"Helicopter start"<<endl; }  
	Vehicle* copy() const { return new Helicopter(*this); }  
};  
class VehicleSurrogate  
{  
public:  
	VehicleSurrogate() : vp(0) {}  
	VehicleSurrogate(const Vehicle& v) : vp(v.copy()) {}  
	VehicleSurrogate(const VehicleSurrogate& v)  
	{  
		vp = (v.vp ? v.vp->copy() : 0);  
	}  
	VehicleSurrogate& operator= (const VehicleSurrogate& v)  
	{  
		if (this != &v)  
		{  
			delete vp;  
			vp = (v.vp ? v.vp->copy() : 0);  
		}  
		return *this;  
	}  
	~VehicleSurrogate() { delete vp; }  
 
private:  
	Vehicle *vp;  
};  
int main()  
{  
	VehicleSurrogate parking_lot[1000]; 
	AutoVehicle v;
	parking_lot[0] = v;//该句等价于下句   
	parking_lot[0] =VehicleSurrogate(v); 

}  


 

抱歉!评论已关闭.