如何正确地将 class 对象的引用传递给 C++ 中的另一个 class-对象
How do I correctly pass a reference of a class object into another class-object in C++
尝试 post 更容易 read/debug 我之前 post 编辑的问题示例。
main.cpp 中的 A 对象通过引用传递给 B 对象似乎最终成为原始 A 对象的副本;也就是说,在 B 对象中对 A 对象执行的操作不会影响在 main.cpp 中创建的 A 对象的实例。鉴于 main.cpp 中的打印命令,它会打印以下内容:17、17、42、17;当我希望程序打印 17, 17, 42, 42.
[main.cpp]
#include <iostream>
#include "A.h"
#include "B.h"
using namespace std;
int main()
{
A a = A();
B b = B();
a.setNumber(17);
b.setA(a);
cout << a.getNumber() << endl; //prints 17
cout << b.getNum() << endl; //prints 17
b.changeNumber(42);
cout << b.getNum() << endl; //prints 42
cout << a.getNumber(); //prints 17
}
[A.cpp]
void A::setNumber(int num)
{
number = num;
}
int A::getNumber()
{
return number;
}
[B.cpp]
void B::setA(A &aObj)
{
a = aObj;
}
void B::changeNumber(int num)
{
a.setNumber(num);
}
int B::getNum() {
return a.getNumber();
}
[[Fields]]
[A.h] int number;
[B.h] A a;
感谢阅读!
B中的成员a应该是某种引用或指针。
这是一个在 B 中使用指针的示例实现:
#pragma once
#include "A.h"
class B
{
public:
void setA(A &aObj)
{
a = &aObj;
}
void changeNumber(int num)
{
a->setNumber(num);
}
int getNum()
{
return a->getNumber();
}
private:
A *a;
};
或参考写作:
#pragma once
#include "A.h"
class B
{
public:
B(A& obj)
: a(obj)
{
}
void changeNumber(int num)
{
a.setNumber(num);
}
int getNum()
{
return a.getNumber();
}
private:
A& a;
};
否则,如果 B 没有引用 A,它不会识别更改,因为它持有自己的副本。
(如果您使用 pointers/references,还要注意您引用的对象的 copy/move 行为和生命周期)
尝试 post 更容易 read/debug 我之前 post 编辑的问题示例。 main.cpp 中的 A 对象通过引用传递给 B 对象似乎最终成为原始 A 对象的副本;也就是说,在 B 对象中对 A 对象执行的操作不会影响在 main.cpp 中创建的 A 对象的实例。鉴于 main.cpp 中的打印命令,它会打印以下内容:17、17、42、17;当我希望程序打印 17, 17, 42, 42.
[main.cpp]
#include <iostream>
#include "A.h"
#include "B.h"
using namespace std;
int main()
{
A a = A();
B b = B();
a.setNumber(17);
b.setA(a);
cout << a.getNumber() << endl; //prints 17
cout << b.getNum() << endl; //prints 17
b.changeNumber(42);
cout << b.getNum() << endl; //prints 42
cout << a.getNumber(); //prints 17
}
[A.cpp]
void A::setNumber(int num)
{
number = num;
}
int A::getNumber()
{
return number;
}
[B.cpp]
void B::setA(A &aObj)
{
a = aObj;
}
void B::changeNumber(int num)
{
a.setNumber(num);
}
int B::getNum() {
return a.getNumber();
}
[[Fields]]
[A.h] int number;
[B.h] A a;
感谢阅读!
B中的成员a应该是某种引用或指针。
这是一个在 B 中使用指针的示例实现:
#pragma once
#include "A.h"
class B
{
public:
void setA(A &aObj)
{
a = &aObj;
}
void changeNumber(int num)
{
a->setNumber(num);
}
int getNum()
{
return a->getNumber();
}
private:
A *a;
};
或参考写作:
#pragma once
#include "A.h"
class B
{
public:
B(A& obj)
: a(obj)
{
}
void changeNumber(int num)
{
a.setNumber(num);
}
int getNum()
{
return a.getNumber();
}
private:
A& a;
};
否则,如果 B 没有引用 A,它不会识别更改,因为它持有自己的副本。 (如果您使用 pointers/references,还要注意您引用的对象的 copy/move 行为和生命周期)