yon*_*oni 4 c++ inheritance static-members
如果类继承了具有静态变量成员的基类,那么它们将是唯一一个与所有继承类共享的成员.
我有几种继承类,并且每一个都有很多实例.我希望每个继承类都有一个单独的静态成员,它与所有实例共享.
怎么做到呢?
谢谢,抱歉我的英语不好.
编辑:
class a{
static int var;};
class b::a{};
class c::a{};
Run Code Online (Sandbox Code Playgroud)
现在,我想的是B的所有实例都会有相同的变种,和C的所有实例都会有相同的变种 ,但该变种 B的将是来自不同变种的C.
我再次对不起我的英语,如果你能纠正我,请你这样做.
Bat*_*hyX 10
您可以使用CRTP工作:
struct YourBaseBaseClass {
// put everything that does not depend on your static variable
};
template <YourSubclass>
struct YourBaseClass : YourBaseBaseClass {
static Member variable;
// and everything that depend on that static variable.
};
struct AClass : YourBaseClass<AClass> {
// there is a "variable" static variable here
};
struct AnotherClass : YourBaseClass<AnotherClass> {
// which is different from the "variable" static variable here.
};
Run Code Online (Sandbox Code Playgroud)
AClass并且AnotherClass都有一个variable静态变量(类型Member),但第一个是静态变量,YourBaseClass<AClass>另一个是来自YourBaseClass<AnotherClass>,它们是两个不同的类.
YourBaseBaseClass是可选的,但是如果你想操纵AClass和AnotherClass使用YourBaseBaseClass*指针你需要它(你不能有一个YourBaseClass*指针,因为YourBaseClass它不是一个类).
并记住定义那些静态变量.
| 归档时间: |
|
| 查看次数: |
1476 次 |
| 最近记录: |