[英]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
实例中存储对其父对象的引用/指针(或者如果可以使用B
则至少要存储对其父对象的n
变量)独立于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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.