简体   繁体   English

在C ++中使用参数初始化成员变量

[英]Initializing a member variable with parameters in c++

I have a class Foo with the ONLY constructer Foo(int length) . 我只有一个构造函数Foo(int length)有一个Foo类。 I also have a class ´Bar´ with the member Foo myFoo = myFoo(100) how would I initialize that? 我还有一个成员为Foo myFoo = myFoo(100)Foo myFoo = myFoo(100)类,该如何初始化呢? I can only initialize it if it has no length parameter in Foo constructer. 如果它在Foo构造函数中没有length参数,则只能对其进行初始化。

Thanks in advance 提前致谢

This questions has come many times. 这个问题已经来过很多次了。 You use constructor initialization lists to do that: 您可以使用构造函数初始化列表来执行此操作:

class Bar
{
    Bar() : myFoo( 100 ) {}

    Foo myFoo;
};

Those initialization lists let you call constructors for base classes as well as for members, and is the intended way to initialize them. 这些初始化列表使您可以为基类和成员调用构造函数,这是初始化它们的预期方法。

Bar::Bar()
: myFoo(100) {

// constructor code

}

I'm not sure if I understood you correctly, but normally members are initialized in constructor initializer lists: 我不确定我是否理解正确,但是通常在构造函数初始化器列表中初始化成员:

class Bar
{
public:
  Bar(); 
private:
  Foo myFoo;
};

Bar::Bar()
// The following initializes myFoo
  : myFoo(100)
// constructor body
{
}

Note that if Bar has several constructors, you have to initialize myFoo in each of them. 请注意,如果Bar有多个构造函数,则必须在每个构造函数中初始化myFoo

C++11 added initialization directly in the member declaration, like this: C ++ 11直接在成员声明中添加了初始化,如下所示:

class Bar
{
  Foo myFoo = Foo(100);
};

However your compiler might not support that yet, or only support it with special flags. 但是,您的编译器可能尚不支持该编译器,或者仅支持特殊标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM