gpt4 book ai didi

c++ - 在几乎相同的结构之间传递成员值

转载 作者:行者123 更新时间:2023-11-30 05:08:25 25 4
gpt4 key购买 nike

我想知道是否有人解决了以下问题,我有两个几乎相同的结构,我需要将值从结构 A 传递到结构 B,它们有一个成员的差异。

示例看起来像这样,我有这些结构:

struct insideA
{
double C1;
double C2;
int C3;
str C4;
};

struct insideB
{
int D3;
str D4;
};

struct A
{
insideA inA;
double c;
std::string d;
} a;

struct B
{
insideB inB;
double c;
std::string d;
} b;

现在结构 A 和 B 几乎相似但不完全相似,如果我们想象 b 已填充,我可以轻松地逐个成员传递值如下:

a.inA.C3 = b.inB.D3;
a.inA.C4 = b.inB.D4;
a.c = b.c;
a.d = b.d;

现在 a 拥有 b 拥有的所有信息,我可以填充 a 的其他成员。所以我的问题是我必须对不同的结构执行大约 30 或 40 次,其中只有结构的第一个成员发生变化,所以有没有比将 a 的值结构成员传递给的结构成员更好的方法b 单独?

最佳答案

让我们使用模板吧!

template <struct Inside>
struct AorB
{
Inside in;
double c;
std::string d;

template <struct OtherInside>
AorB& operator=(const AorB<OtherInside>& that) {
in = that.in;
c = that.c;
d = that.d;
}
};

struct A : AorB<insideA>
{
template <struct OtherInside>
A& operator=(const AorB<OtherInside>& that) {
AorB<insideA>::operator=(that);
return *this;
}
};

struct B : AorB<insideB>
{
template <struct OtherInside>
B& operator=(const AorB<OtherInside>& that) {
AorB<insideB>::operator=(that);
return *this;
}
};

您也可以将这个想法扩展到内部类。

关于c++ - 在几乎相同的结构之间传递成员值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46850423/

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