gpt4 book ai didi

c++ - 使用组合类中计算的数据构造成员类

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

我有一个 Itch 类,它是 Scratch 类的成员。我想在 Scratch 构造函数中进行一些计算,并将这些计算的结果传递给实例化 Itch 对象。我最好的猜测如下,但这会返回垃圾:

#include <iostream>

class Itch {
public:
int N;
Itch(int n) {N = n;}
};

class Scratch {
private:
int N;
public:
Itch it;
Scratch(int n);
};

Scratch::Scratch(int n) : it(N) // here is where I want to use new data
{
// do some silly things
int temp = 5;
temp += n + 45;
N = temp - 1;
}

int main() {
int n = 1;
Scratch sc(n);

std::cout << sc.it.N << "\n";
}

有没有标准的方法来做到这一点?

最佳答案

初始化列表中的事情发生在构造函数代码中的事情之前。因此,您不能用构造函数中的代码影响初始化列表中的任何内容。你有几个选择。

一个合理的方法是拥有一个 Itch * 成员而不是 Itch,并在它准备好时初始化它,例如:

class Scratch {
...
Itch *it;
...
};

Scratch::Scratch(int n) : it(NULL)
{
// do some silly things
int temp = 5;
temp += n + 45;
N = temp - 1;
it = new Itch(N); // <- now you have enough info to instantiate an Itch
}

除非你使用 auto_ptr,否则你必须记住在析构函数中进行清理:

Scratch::~Scratch () {
delete it;
}

另一种合理的方法是将 n 传递给 Itch 构造函数,让它在那里而不是在 Scratch 中进行计算,甚至可能允许 Itch 确定 N,例如:

class Itch {
private:
int N;
public:
Itch (int n);
int getN () const { return N; }
}

Itch::Itch (int n) {
// do some silly things
int temp = 5;
temp += n + 45;
N = temp - 1;
}

Scratch::Scratch (int n) : it(n) {
// you can either remove Scratch::N altogether, or I suppose do:
N = it.getN();
// ... do whatever makes sense, try not to have redundant data.
// (also ask yourself if Scratch even *needs* to know N, or at
// least if it can just use it.getN() everywhere instead of
// keeping its own copy.)
}

另一种方法,在我看来有点奇怪,但在某些情况下仍然可行,例如从 n 计算 N 的静态函数(成员或非成员),您可以在初始化列表中使用它,例如:

static int doSillyThings (int n) {
int temp = 5;
temp += n + 45;
return temp - 1;
}

Scratch::Scratch(int n) : N(doSillyThings(n)), it(N)
{
}

选择最干净、最可维护和易于阅读的代码。就我个人而言,我更喜欢第一个选项,Itch *,因为它合乎逻辑且非常清晰:您进行初始化 Itch 所需的计算,然后对其进行初始化.

您应该稍微考虑一下您的代码。如果 ScratchN 总是等于 it.N,那么你真的需要两个 N 吗?

还有其他选择(包括完全重构您的代码,这样您就不必拥有 ScratchItch 成员,或者这样你就不必让 it 依赖于对 Scratch 的构造函数参数进行的额外计算,但这实际上取决于具体情况),但希望这能激发你的灵感一点点。


顺便说一下,您的代码返回垃圾的原因是因为 N 在您将它传递给 Itch 构造函数时是垃圾.在您初始化它之前,它是未初始化的,而在 it(N) 所在的位置,您还没有初始化 N

关于c++ - 使用组合类中计算的数据构造成员类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28892257/

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