BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #42491同步于 2010/8/18
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

C++问题

baimushan
2010/8/18镜像同步1 回复
vehicle.h class Vehicle { public: virtual void start(void)const=0; virtual Vehicle* copy(void)const=0; virtual ~Vehicle() {} }; class SurrogateVehicle { public: SurrogateVehicle(); SurrogateVehicle(const Vehicle& vehi) ; SurrogateVehicle(const SurrogateVehicle& sv ); SurrogateVehicle & operator=(const SurrogateVehicle& sv); ~SurrogateVehicle(); void start(); private: Vehicle* vehicle; }; class truck:public Vehicle { void start()const ; truck* copy() const ; }; class motocycle:public Vehicle { void start()const ; motocycle* copy() const ; }; vehicle.cpp #include "vehicle.h" #include <iostream> SurrogateVehicle::SurrogateVehicle():vehicle(0) { } SurrogateVehicle::SurrogateVehicle(const Vehicle& vehi):vehicle(vehi.copy()) { //vehicle = vehi.copy(); std::cout<<"test ppp"; } SurrogateVehicle::SurrogateVehicle(const SurrogateVehicle& sv ):vehicle(sv.vehicle?sv.vehicle->copy():0) { } SurrogateVehicle& SurrogateVehicle::operator =(const SurrogateVehicle &sv) { if ( vehicle ) { delete vehicle; std::cout<<std::endl; } std::cout<<"test="; vehicle = sv.vehicle?sv.vehicle->copy():0; return *this; } void SurrogateVehicle::start() { vehicle->start(); } SurrogateVehicle::~SurrogateVehicle() { if( vehicle) { delete vehicle; } } truck* truck::copy()const { std::cout<<"truck construction"<<std::endl; return new truck(*this); } void truck::start()const { std::cout<<"truck start"<<std::endl; } motocycle* motocycle::copy()const { std::cout<<"motocycle construction"<<std::endl; return new motocycle(*this); } void motocycle::start()const { std::cout<<"motocycle start"<<std::endl; } main.cpp #include "vehicle.h" #include <iostream> int main(int argc,char *argv[]) { truck first; motocycle second; //SurrogateVehicle stop_part[100]; SurrogateVehicle test; test = first ; system("pause"); return true; } 询问 在运行时 调用了两次copy函数 truck construction test ppptest=truck construction 不明白为什么。
订阅后,新回复会通过你的通知中心匿名送达。
1 条回复
landiya机器人#1 · 2010/8/18
赋值的时候应该是生成临时对象了 【 在 baimushan 的大作中提到: 】 : vehicle.h : class Vehicle : { : ...................