【问题标题】:Define getter for child class variable inside parent为父类中的子类变量定义getter
【发布时间】:2020-06-20 21:43:11
【问题描述】:

我有一个项目,我正在使用指向父类的指针访问多个类。我需要知道指针所指的是哪个子类,所以我将一个不同的整数 ID 号添加到每个子类作为常量类变量。

我需要使用指针访问这个变量,所以我为那个变量写了一个getter函数。由于 getter 函数的代码对于所有子类都是相同的,因此我尝试在父类中定义该函数。这大致导致了下面的代码:

class Parent {
  public:
    virtual void func();

    // Getter function
    uint8_t getID() {
      return classID;
    }

    // Set ID to a default value
    const uint8_t classID = 0;
};

// One of many child classes
class A: public Parent {
  public:
    void func() {//do something}

    const uint8_t classID = 1;
};

int main(){
    Parent* childPointer = new A;
    uint8_t currentID = childPointer -> getID();
}

但是,运行它会导致 currentID 等于 Parent.classID 而不是 A.classID

getID 函数设为虚函数并在每个子类中定义它可以使其按预期工作,但这会导致大量重复代码。我想知道是否有办法在 Parent 类中定义一次 getter 函数,并使其返回正确的值?否则,有没有更清洁的方法呢?

【问题讨论】:

    标签: c++ class oop polymorphism parent-child


    【解决方案1】:

    在 C++ 中,每个类都有自己的命名空间。在您的代码中,您在 Parent 命名空间中有一个 classID,在 A 命名空间中有一个 classID。所以 A 的每个实例实际上都有 2 个 classID。不过,getID() 函数只能看到 Parent 命名空间中的 classID。这就是为什么它只返回 0。

    更好的方法是定义将在 Parent 中初始化 classID 的构造函数:

    #include <cstdint>
    
    class Parent {
      public:
        Parent(): classID(0){}; //Default Parent initializes with 0
        Parent(uint8_t ID): classID(ID){}; //Constructor to be called by children
    
        virtual void func(){};
    
        // Getter function
        uint8_t getID() {
          return classID;
        };
    
        const uint8_t classID;
    };
    
    // One of many child classes
    class A: public Parent {
      public:
        A(): Parent(1){}; //Every A calls Parent(uint8_t) constructor
    
        void func() {};//do something
    
        //const uint8_t classID = 1;  //This is not needed anymore
    };
    
    int main(){
        Parent* childPointer = new A;
        uint8_t currentID = childPointer -> getID();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 2011-11-16
      相关资源
      最近更新 更多