问题描述
我不习惯c ++,我在写一个构造函数时遇到问题。
看到这个例子,是我正在处理的代码的一个简短版本:
I'm not used to c++ and I'm having a problem writing a constructor.
See this example, is a short version of the code I'm working on:
class B {
public:
B(int x);
}
class A {
public:
B b;
A(){
// here I have to initialize b
}
}
这会抛出编译器错误,因为我需要在A的构造函数中初始化b,因为B没有默认构造函数。
That throws a compiler error since I need to initialize b in A's constructor because B does not have a default constructor.
在初始化列表中做,但是B(int x)参数是一个值,我必须用一些算法计算,所以我不知道这应该如何正确完成,或者如果我缺少的东西或做它错误。
I think I have do it in the initialization list, but the B(int x) argument is a value I have to calculate with some algorithm, so I don't know how this should be properly done, or if I'm missing something or doing it wrong.
在其他语言如java中,我将引用B并在A的构造函数中初始化它,然后在其他代码之后,我需要获取初始化的值。
In other language like java I would have a reference to B and initialize it inside the A's constructor after the other code I need to get the value for the initialization.
在这种情况下,初始化b的正确方法是什么?
What would be the right way to initialize b in this case?
推荐答案
您可以在构造函数初始化列表中调用函数
You can invoke functions in your constructor initializer list
class B {
public:
B(int x);
}; // note semicolon
class A {
public:
B b;
A()
:b(calculateValue()) {
// here I have to initialize b
}
static int calculateValue() {
/* ... */
}
}; // note semicolon
请注意,在初始化器列表中,类被认为是完全定义的,看到稍后宣布的成员。还最好不要在构造函数初始化器列表中使用非静态函数,因为并不是所有的成员都在这一点上被初始化。静态成员函数调用很好。
Note that in the initializer list, the class is considered completely defined, so you can see members declared later on too. Also better not use non-static functions in the constructor initializer list, since not all members have yet been initialized at that point. A static member function call is fine.
这篇关于c ++如何写一个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!