如何使嵌套类的变量对父类的每个实例都是静态的

How to make variable of nested class static for each instance of parent class?

本文关键字:实例 静态 嵌套 何使 变量 父类      更新时间:2023-10-16

例如,在下面的示例中,我希望能够将x.nest1.ny.nest1.n设置为不同的值,但强制x.nest1.n === x.nest2.ny.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   :(

听起来nA的属性,而不是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;
};