从 C# 到 Qt,我无法理解如何正确翻译以下常见习语 (C#):
class Customer {
public property List<Address> Addresses { get; }
}
class AnotherClass {
public void SetAsShipping(List<Address> addresses) {
foreach(var address in addresses)
if (address.IsMatch(_shipping))
address.IsShipping = true; // This is the important part
}
}
var cust = new Customer();
var another = new AnotherClass();
another.SetAsShipping(cust.Addresses);
我有以下 C++:
class Customer {
public:
QList<Address> addresses() const { return _addresses; }
private:
QList<Address> _addresses;
};
class AnotherClass {
public:
void setAsShipping(QList<Address> addresses);
};
AnotherClass::setAsShipping(QList<Address> addresses) {
QList<Address>::iterator address;
for (address = addresses->begin(); address != addresses->end(); ++address)
if (address->isMatch(_shipping))
address->setIsShipping(true); // This is modifying a copy :(
}
Customer cust;
AnotherClass another;
another.setAsShipping(cust.addresses());
我知道我可以将 _addresses 作为引用返回,然后通过引用传递它,但显然这可能会导致问题,因为我的 Customer 实例可能会在对 _addresses 的引用之前超出范围,这将导致“悬空引用”。我从搜索中发现了很多。我没有找到应该做的事情。显然,有一种标准的 C++ 方法可以做这种事情,但是我的大脑被困在托管代码模式中,它没有跳出来。我应该如何编写这段代码,以便地址列表可以被 AnotherClass 修改?