gpt4 book ai didi

c# - 在 C++ 中的两个类之间共享(QList 的)实例

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:58:42 24 4
gpt4 key购买 nike

从 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 可以修改地址列表?

最佳答案

在您的 C# Customer 类中,Addresses 只是公共(public)属性,您也可以在 C++ 中这样做,但这显然不是一个好的设计。

class Customer {
public:
QList<Address> _addresses;
};

AnotherClass::setAsShipping(QList<Address>& addresses) {
for (QList<Address>::iterator address = addresses->begin();
address != addresses->end(); ++address)
{
if (address->isMatch(_shipping)) {
address->setIsShipping(true); // Now modify the real object
}
}
}

为了以更好的方式做到这一点,让我们重新考虑您的 C# 设计。

1.为什么是List<Address> Addresses公开?

2.SetAsShipping 真的应该属于另一个类吗?看起来它属于 Customer 类?

3.进一步增强,可以使用Qlist算法代替for循环来查找地址吗?

class Customer
{
public:
void setAsShipping(const Address& address)
{
for (QList<Address>::iterator address = addresses->begin();
address != addresses->end(); ++address)
{
if (address->isMatch(_shipping)) {
address->setIsShipping(true); // Now modify the real object
}
}
}
private:
QList<Address> _addresses;
};

customer cust;
AnotherClass another;

cust.setAsShipping(another.address());

现在还存在悬空引用问题吗?

关于c# - 在 C++ 中的两个类之间共享(QList 的)实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13597507/

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