C++交换来自同一类成员的参数值,处理多个类



所以基本上我有一个系统类,它被构建为一系列平面和球体(也是类(。平面和球体(元素(是类Element_CR的子类。

例如,系统看起来像这样 ->

System system0 = {PlaneElement0, Sphere0, Sphere1, PlaneElement1};

现在每个平面和球体都有一个高度参数。 球体和平面有自己的高度和其他参数的"设置"和"获取"功能。

Sphere0.set(2.0); // sets the height to 2.0
Sphere0.get();    // returns the height value

我的目标是能够采用 2 个系统 A 和 B(具有相同的平面/球体系列(并交换它们的高度参数。

System systemA = {Sphere0, Sphere1,PlaneElement0};
System systemB = {Sphere2, Sphere3,PlaneElement1};

所以让我们来看看我的简化代码

class Element_CR {
public:
Element_CR() {};
~Element_CR() {};
virtual Element_CR* crossover_ptr(Element_CR* A, Element_CR* B)=0;
}    
//now the first subclass PlanElement
class PlanElement : public Element_CR
{
public:
PlanElement() {};
PlanElement(double semiHeight) :
mSemiHeightPlanParam(semiHeight)
{
buildPlanGeometry_LLT();
};
~PlanElement() {};
//function for setting the height
void set(double height);
//function that returns the height
double get();   
//now the virtual override function 
virtual Element_CR* crossover_ptr(Element_CR* planA, Element_CR* planB) override;

//as I mentioned before the goal is to swap the values between the plane A and plane B Heights.
// So first just getting plane A to have the plane B Height would be fine.
//now the definition of the crossover_ptr function for the Plane element
Element_CR* PlanElement::crossover_ptr(Element_CR* planA, Element_CR* planB) {
PlanElement crossPlan = planA;

//so here i get errors, since when i type "planB." 
//it doesnt show me the "set" function that has been defined in the PlaneElement class
//it says basically "Element_CR* A  expression must have class type"
crossPlan.set(planB.get());
return &crossPlan
}

现在,球体元素(Element_CR的第二个子类(也应该这样做,但这可以通过类比方式解决平面元素。球体元素类获得相同的"虚拟Element_CR* crossover_ptr(Element_CR* sphereA, Element_CR* sphereB( 覆盖;"

所以最后我希望能够循环两个系统(由元素构建(,并交换(两个系统的(元素的高度。

这可能是一个基本问题,但我是 c++ 的新手(可能和大多数发布问题的人一样(。 我将非常感谢任何建议和帮助, 莱皮纳

Element_CR* PlanElement::crossover_ptr(Element_CR* planA, Element_CR* planB) {
PlanElement* crossPlanA = dynamic_cast<PlanElement*>(planA);
PlanElement* crossPlanB = dynamic_cast<PlanElement*>(planB);
if(crossPlanA != nullptr && crossPlanB != nullptr) {
double tmp = crossPlanA->get();
crossPlanA->set(crossPlanB->get());
crossPlanB->set(tmp);
return ... // Whatever you want to return?
}
return nullptr;
}

我认为这符合你想做的事情。它首先检查两个元素是否真的是PlanElements(您可以更改它以考虑平面和球体(,如果是,则交换值。如果它们不是类型PlanElement,则返回nullptr。你必须考虑你想归还什么,我无法弄清楚那里的感觉。

你可能想重新考虑你的设计,我认为这并不反映你真正想要做什么,因为它只专门针对两个子类,因此你实际上不想在基类中使用该方法。

最新更新