使用在组合类中计算的数据构造成员类

Consruct Member Class using Data computed in Composing Class

本文关键字:数据 成员类 计算 组合      更新时间:2023-10-16

我有一个类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.)
}

另一种方法,IMO有点奇怪,但在某些情况下仍然可能,是使用静态函数(成员或非成员),从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

相关文章: