如何避免C++派生类中基类成员的重复副本
How to Avoid Duplicate copies of Base Class Members in Derived Class in C++
在我的项目中,有一个基类,有 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;
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在模板类中返回成员变量的副本
- 在实例副本之间共享的类成员
- 保留对象成员变量的本地副本
- 是否有一种方法可以始终通过值(制作副本)而不是在使用类成员函数时通过参考来传递
- 如何为同一类对象的成员函数保留单独的变量副本?
- 混合共享/静态库时静态成员的多个副本
- 设计一个具有大型成员的C++类,而这些成员很少在副本中访问
- 您应该将自动副本移到成员中还是将其保留
- 如何在基类中获取受保护成员的"真实"副本
- 无法访问类 sf::不可复制中的私有成员.副本在哪里?C++
- 删除结构的成员,并将其重新制作为其他内容的副本,而不使用 new
- 如何避免C++派生类中基类成员的重复副本
- C++类:在成员函数中创建"this"类的副本
- 使用已删除的副本构造函数和初始值设定项列表重载调用类定义中的成员构造函数
- C++通过对构造函数的引用传递.成员将是一个完整的私人副本
- 使复制的成员引用变量引用副本的成员,而不是原始成员的成员
- 在c++中通过成员函数返回引用比返回副本快
- 非静态成员函数,为每个对象创建生成一份机器码副本
- 赋值运算符-每个成员或二进制副本