从继承的对象检索信息

retrieving information from inherited objects

本文关键字:检索 信息 对象 继承      更新时间:2023-10-16

我正在尝试实现从简单到复杂的继承对象的层次结构,以使对象具有尽可能多的面向对象功能的方式进行,但我填补了这项工作可以在许多方面得到改进。非常欢迎任何建议。特别是我不知道如何使用继承功能来解决以下问题的安全方法:

  1. 对象 Atom 包含从更简单的对象 Contraction 继承的对象 BasisFunction 向量。但是在 Atom 中,我需要访问每个 BasisFunction 的向量 zeta 和 C 中包含的信息。如何修改它以使其成为可能?
  2. 层次结构中的所有对象都是可复制的吗?如何引入面向对象的功能?
  3. 最后,我想有一个分子单例。如何定义它?
  4. 我关注的是这种实施方法的表现。哪里可以改进?

此时,我将显示代码:

#include <iostream>
#include <armadillo>
using namespace std;
using namespace arma;

class Contraction{
protected:
  vector<double> zeta;
  vector<double> c;
  vec A;
public:
  Contraction(){} /*contructor*/
 Contraction(vector<double> Zeta,vector<double> C, vec a):zeta(Zeta),c(C),A(a){}
 /*contructor*/
  ~Contraction(){} /*destructor*/
  bool deepcopy(const Contraction& rhs) {
    bool bResult = false;
    if(&rhs != this) {
      this->zeta=rhs.zeta;
      this->c=rhs.c;
      this->A=rhs.A;
      bResult = true;
    }
    return bResult;
  }
 public: 
  Contraction(const Contraction& rhs) { deepcopy(rhs); }
  Contraction& operator=(const Contraction& rhs) { deepcopy(rhs); return *this; }
};

class BasisFunction: public Contraction{
 protected:
  vector<int> n;
  vector<int> l;
  vector<int> m;
  bool deepcopy(const BasisFunction& rhs) {
    bool bResult = false;
    if(&rhs != this) {
      this->zeta=rhs.zeta;
      this->c=rhs.c;
      this->A=rhs.A;
      this->n=rhs.n;
      this->l=rhs.l;
      this->m=rhs.m;
      bResult = true;
    }
    return bResult;
  }
 public:
  BasisFunction(){};/*How to define this constructor to initialize the inherited elements too?*/
  ~BasisFunction(){};
};

class Atom{
 protected:
  int Z;
  vec R;   ///Position
  vec P;   ///Momentum
  vec F;   ///Force
  double mass;
  vector<BasisFunction> basis;
 public:
  /*Here I need to define a function that uses the information in vectors c_i and zeta_i of the vector basis, how could it be achieved?*/
};

vector<Atom> Molecule; /*I nedd transform this in a singleton, how?*/

提前谢谢。

  1. 如何修改它以使其成为可能?您应该公开Contraction受保护的字段,或者Contraction Getter/Setter 方法以访问此文件,或者重新设计类的所有层次结构以将此字段恰好放在需要它们的位置。
  2. 层次结构中的所有对象都是可复制的吗?如何引入面向对象的功能?类中没有私有复制构造函数/赋值运算符,它们没有指向其中数据的原始指针,因此可以安全地复制它们。
  3. 最后,我想有一个分子单例。怎么可能 定义?您不能从向量分子接收单例,因为这是对象的包含器而不是对象本身。这里不需要单例,因为你实际上只能在范围内有一个"分子"命名向量。但是,如果你想让signleton保存分子数据,你应该添加一个类shell:

class Molecule
{
public:
    static Molecule & Instance() { static Molecule instance; return instance; }
    const vector<Atom> & GetMyData() const { return data; }
    vector<Atom> & GetMyData() { return data; }
private:
    Molecule() {};
    Molecule(const Molecule & rhs);
    const Molecule & operator=(const Molecule & rhs);
        
    vector<Atom> data;
};
这是迈耶斯的经典单例实现。

  1. 我担心这种方法对 实现。哪里可以改进?为了提高性能,您需要删除处理虚拟函数调用和间接寻址的每个算法步骤中的所有内容。在你的代码中,这意味着你真的不应该在你的基类中实现get/set方法,因为现在它们是逻辑结构 - 只是有序的数据持有者。如果您经常查看 zeta、c 和其他字段,您必须可以直接访问那里。