2

例如在下面的例子中,我希望能够设置x.nest1.n不同的值,但是强制和- 如何实现这一点?y.nest1.nx.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   :(
4

3 回答 3

4

听起来像是n的属性A,而不是B。您应该为其中一个或其父级提供B成员引用nA

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 ) {}
};
于 2013-05-16T00:34:25.223 回答
1

你不能使用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) { ... }
};
于 2013-05-16T00:35:21.407 回答
0
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;
};
于 2013-05-16T00:33:20.337 回答