使用在组合类中计算的数据构造成员类
Consruct Member Class using Data computed in Composing Class
我有一个类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
所需的计算,然后初始化它
你应该仔细考虑一下你的代码。如果Scratch
的N
总是等于it.N
,那么您真的需要两个N
吗?
还有其他选择(包括完全重组代码,这样您就不必拥有Scratch
的Itch
成员,或者不必让it
依赖于对Scratch
的构造函数参数进行的额外计算,但这确实取决于具体情况),但希望这能给您一点启发。
顺便说一句,代码返回垃圾的原因是,在将N
传递给Itch
构造函数时,它是垃圾。在初始化它之前,它是未初始化的,在it(N)
所在的位置,您还没有初始化N
。
相关文章:
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 如何在c++中定义以struct为数据成员的类中的构造函数
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 将私有数据成员添加到野牛生成的类中
- 在类 A 中创建类型为 B 类的向量 - 访问数据 [C++] [成员在两个类中都是私有的]
- 访问数据成员(本身是对象)的数据成员,就好像它们是类成员一样
- 在 C++ 中,默认情况下构造函数为类的数据成员提供的值是多少?
- 大家好,当一个类有一个向量作为它的数据成员时,为什么它的大小总是24?
- C++ 使用派生类方法更改基类数据成员
- "Class1"类"Class2"对象作为私有数据成员。如何通过"Class 2"函数引用"Class1"对象?
- 如何使用数据成员填充派生类的对象到基类的指针数组中
- 何时需要定义类的静态数据成员 (un/-)
- 使用 delete [] 运算符取消分配类中数据成员的内存
- 为什么c++中类的大小取决于数据成员的公共/私有状态
- 如何在C++中使用类对象访问指针数据成员
- 为什么静态数据成员不能在c++11中的类中初始化
- 不可复制类数据成员的统一初始化导致gcc错误
- 类模板静态数据成员定义/声明/初始化
- 如果类在 C++ 中具有常量或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?
- 初始化类C++中的静态数据成员(类)