gpt4 book ai didi

c++ - 如何为父类的每个实例使嵌套类的变量成为静态变量?

转载 作者:搜寻专家 更新时间:2023-10-31 00:39:13 25 4
gpt4 key购买 nike

例如在下面的例子中,我希望能够设置 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 一个成员 referencen 或其父级 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 ) {}
};

关于c++ - 如何为父类的每个实例使嵌套类的变量成为静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16577127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com