【发布时间】:2017-10-21 07:28:04
【问题描述】:
我有一个包含几个实例变量的类 A 和一个引用该类并更改实例变量的类 B。在 B 类更改这些变量之后,您会认为这些变量会在该类的原始实例中发生更改,但在这种情况下它们不会。为什么会发生这种情况,我该如何解决?
class Foo {
public:
int x;
int y;
Foo() {
}
Foo(int x, int y) {
this->x = x;
this->y = y;
}
};
class Bar {
public:
Foo foo;
Bar() {
}
Bar(Foo& foo) {
this->foo = foo;
}
void Swap() {
int tmp = foo.x;
foo.x = foo.y;
foo.y = tmp;
}
};
int main()
{
Foo foo(4, 8);
Bar bar(foo);
std::cout << "this is x: " << foo.x << std::endl; //prints 4
std::cout << "this is y: " << foo.y << std::endl; //prints 8
bar.Swap();
std::cout << "this is x: " << foo.x << std::endl; //prints 4, but should print 8
std::cout << "this is y: " << foo.y << std::endl; //prints 8, but should print 4
}
【问题讨论】:
-
欢迎来到 Stack Overflow。请花时间阅读The Tour 并参考Help Center 中的材料,您可以在这里问什么以及如何问。
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行逐行检查您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 edit 您的问题包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
Bar包含源Foo的副本,而不是对源Foo的引用。Foo通过引用传递到函数中,但随后被复制。 -
user4581301 是对的,你应该使用
foo->bar.Swap();
标签: c++ oop pass-by-reference