本文介绍了有条件地启动对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 大家好, 我是新手,很抱歉这个问题在这里不合适。 不过我试试。 --- 假设我有一个CTraffic类,其中几个类的对象是 CVehicle移动。但是,类CVehicle是一个抽象基础 类,因为它的每个对象都是子类CCar或子类的成员 CBicycle。 因此,如果我在CTraffic中定义一个CVehicle,我可以制作一个if / else块 ,它决定我们是在主要道路上还是在自行车道上。在里面 这个块我可以声明并初始化正确的对象为 CCar * pVehicle = new CCar(); 或 CBicycle * pVehicle = new CBicycle(); 然后在我的新指针pVehicle上执行一些CVehicle函数(如MoveFroward(int dist))。 --- 然而,有些东西会接受这个概念,因为 调试会给出错误 错误C2065:''pBac'':未声明的标识符 在我第一次使用 if / else块之外的新pVehicle对象的行上。 如需任何帮助或努力:请提前预订!!! jHi all,I''m a newbe, so sorry if this question would be inappropriate here.Nevertheless I try.---Suppose I have a class CTraffic in which several objects of classCVehicle move around. However, class CVehicle is an abstract baseclass, since every object of it is member of subclass CCar or subclassCBicycle.So if I define a CVehicle inside CTraffic, I can make an if/else blockthat decides if we''re on the main road or on the bicycle path. Insidethis block I can then declare and initialize the right object asCCar* pVehicle = new CCar();orCBicycle* pVehicle = new CBicycle();and afterwards perform some CVehicle functions (like MoveFroward(intdist)) on my new pointer pVehicle.---However, something seams to be wrond with this concept, becausedebugging gives an errorerror C2065: ''pBac'' : undeclared identifieron the line where I first use the new pVehicle object outside theif/else block.For any help or effort: thx in advance!!!j推荐答案 RaviRavi 我认为这很简单够了,你有这个 if(something) CCar * pVehicle = new CCar(); else CBicycle * pVehicle = new CBicycle(); 这些车辆只存在于if else语句中。你想要的是 这个 CVehicle * pVehicle; if(something) pVehicle = new CCar(); else pVehicle = new CBicycle(); 现在因为pVehicle在if之外声明else语句它存在 $ if $ if语句之外的b $ b。 注意pVehicle的类型已经改为你的抽象基类 应该如何。 johnI think it''s simple enough, you have thisif (something)CCar* pVehicle = new CCar();elseCBicycle* pVehicle = new CBicycle();Those vehicles only exist inside the if else statement. What you want isthisCVehicle* pVehicle;if (something)pVehicle = new CCar();elsepVehicle = new CBicycle();now because pVehicle is declared outside the if else statement it existsoutside the if else statement.Note the type of pVehicle has changed to your abstract base class whichis how it should be.john 你的概念本身没有错,但你有一个明确的问题 编译代码。编译器不知道pBac是什么。除了你的编译错误之外你还没有提到它。 如果你想要真正的帮助,你需要发帖你的完整代码。不能通过模糊的描述来诊断问题。 - 约翰拉特利夫Nothing wrong with your concept per se, but you have a definite problemcompiling your code. The compiler has no idea what a pBac is. Neither doI since you didn''t mention it aside from your compile error.If you want real help, you''ll need to post your complete code. Can''tdiagnose problems from a vague description.--John Ratliff 这篇关于有条件地启动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 05-15 23:29