繁体   English   中英

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

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

例如,在下面的示例中,我希望能够将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实例中存储对其父对象的引用/指针(或者如果可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM