如何避免C++派生类中基类成员的重复副本

How to Avoid Duplicate copies of Base Class Members in Derived Class in C++

本文关键字:成员 副本 基类 何避免 C++ 派生      更新时间:2023-10-16

在我的项目中,有一个基类,有 3 个不同的派生类。我在基类中有一些宏变量写为 const int。所有派生成员都将访问这些成员,并将看到相同的值。由于它是一个常量,并且不会改变,因此维护 3 个不同的值将浪费空间。因此,我想要一种方法来维护基类 const 成员的一个副本,以便所有派生类都使用相同的副本。

 //Base.hpp
 Class Base {
       const int ZER0;
       const int ONE;
 };
 //Derived1.hpp
 class Derived1:public Base {
      int some_method1(); 
 };
  //Derived1.cpp
  int Derived1::some_method1() {
    int value = ZERO;
  }
 //Derived2.hpp
 class Derived2:public Base {
    int some_method2();
 };
//Derived2.cpp
int Derived2::some_method2() {
   int value = ONE;
}
//main.cpp
Derived1 d1;
d1->some_method1();
Derived d2;
d2->some_method2();

在这两种方法中,值都是常数,但 ZERO 和 ONE 仍然具有不同的空间。有没有办法,我只保留一个副本?我可以想到静态变量。是否可以在类中使用静态,在哪里初始化静态变量。请指教。

PS:这个问题可能是重复的,但我找不到类似单词的东西,如果你觉得是,请随时重定向到相应的文章/问题;

如果我

理解正确,枚举会做你想要的吗?

class Base
{
    enum 
    {
        ZERO,
        ONE
    };
};

我认为您可以使用虚拟基础继承来维护一个基础副本..

//Base.hpp
class Base {
public:
    Base() {}
    virtual ~Base() {}
protected:
    static const int ZER0;
    static const int ONE;
};
//Base.cpp
const int Base::ZER0 = 0;
const int Base::ONE = 1;
//Derived1.hpp
class Derived1 : public virtual Base {  //using virtual keyword here maintains one copy of base class, thus one copy of ONE and ZERO for all objects since they are static members of Base. You must read about diamond problem of virtual inheritence to understand this properly.
public:
    Derived1() :Base() {}
    int method1();
};
//Derived1.cpp
int Derived1::method1() {
    int value = ZER0;
    return value;
}
//Derived2.hpp
class Derived2 : public virtual Base {
public:
    Derived2() :Base() {}
    int method2();
};
//Derived2.cpp
int Derived2::method2() {
    int value = ONE;
    return value;
}
//main.cpp

int main() {
    Derived1 d1;
    d1.method1();  // . instead of -> , -> is used for member access through pointers
    Derived2 d2;
    d2.method2();
    return 0;
}