C++ 交换相同 class 成员的参数值,处理多个 classes

C++ swap the parameter values from same class members, working on multiple classes

所以基本上我有一个系统 class,它是由一系列平面和球体(也是 classes)构建的。平面和球体(元素)是 class Element_CR.

的子classes

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

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

现在每个平面和球体都有一个高度参数。 球体和平面有自己的 "set" 和 "get" 函数用于高度和其他参数。

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

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

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 的第二个子class)进行处理,但这可以类推到平面元素。球体元素 class 得到相同的 "virtual Element_CR* crossover_ptr(Element_CR* sphereA, Element_CR* sphereB) override;"

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

这可能是一个基本问题,但我是 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(您可以更改它以考虑 Planes 和 Spheres),如果是,它交换值。如果它们不是 PlanElement 类型,它 returns nullptr。你必须考虑你想要什么 return,我想不通。

您可能想重新考虑您的设计,我不认为这反映了您真正想要做的事情,因为它仅专门用于两个子class,因此您实际上不想拥有基础 class.

中的方法