如何使嵌套类的变量对父类的每个实例都是静态的
How to make variable of nested class static for each instance of parent class?
例如,在下面的示例中,我希望能够将x.nest1.n
和y.nest1.n
设置为不同的值,但强制x.nest1.n === x.nest2.n
和y.nest1.n === y.nest2.n
-如何实现这一点?
struct A {
...
struct B {
static int n;
...
};
B nest1;
B nest2;
};
int A::B::n = 0;
...
A x, y;
x.nest1.n = 1;
y.nest1.n = 2; // want to be able to set seperately from x.nest1.n
std::cout << x.nest1.n; // prints 2 :(
听起来n
是A
的属性,而不是B
。你应该给B
一个成员引用给n
或者它的父A
。
struct A {
struct B {
int &n;
B( int &in_n ) : n( in_n ) {}
};
int n;
B nest1;
B nest2;
A::A() : n( 5 ), nest1( n ), nest2( n ) {}
};
不能使用static
变量,因为static
意味着,根据定义,类的所有实例共享静态成员。
一种解决方法是将B::n
作为非静态成员变量移动到A
中:
struct A {
...
int n;
struct B {
...
};
B nest1;
B nest2;
};
如果(我假设)你需要从B
方法访问这个变量,那么通常的解决方案是在每个B
实例中存储一个指向父变量的引用/指针(或者至少是指向父变量的n
变量,如果B
可以独立于A
使用):
struct A {
...
int n;
struct B {
A& parent;
B(A& parent_) : parent(parent_) { ... }
...
};
B nest1;
B nest2;
A() : nest1(*this), nest2(*this) { ... }
};
struct A {
...
struct B {
int n;
...
};
void setN(int n) {
nest1.n = n;
nest2.n = n;
}
B const& getNest1() const
{ return nest1; }
B const& getNest2() const
{ return nest2; }
private:
B nest1;
B nest2;
};
相关文章:
- 静态数据成员模板专用化的实例化点在哪里
- 如果 std::vector::clear() 不是静态的,如何在没有实例的情况下调用它?
- C++两个源文件之间共享的枚举的静态实例
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 如何在没有实例的情况下获取非静态方法的类型?
- 名称隐藏对静态函数继承的实例使用
- 如何正确实例化静态字段 tat 是另一个类对象
- 初始值设定项列表是否足够静态以允许实例化模板?
- 类外的静态变量实例化
- c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?
- 实例成员与静态成员与非类方法的开销
- 生成代码(在编译时)以调用模板的每个实例化的静态函数
- 引用的静态强制转换强制模板实例化,其中不完整的类型很好
- 让类方法为每个实例保存不同的静态变量
- 包含不同大小静态数组的类的多个实例
- 作为成员的静态类模板实例会导致未解析的外部符号错误
- 静态模板成员函数的实例化?
- 为什么可以在没有实例变量的情况下访问静态回调方法中的静态成员变量?
- 我们如何在模板类中使用静态映射,模板类的每个实例化都应该使用相同的映射
- cpp 静态对象实例化